Mirror of :pserver:cvs@cvs.fefe.de:/cvs libowfat https://www.fefe.de/libowfat/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

43 lines
1.0 KiB

  1. #include "fmt.h"
  2. /* write int in least amount of bytes, return number of bytes */
  3. /* as used in ASN.1 length */
  4. size_t fmt_asn1derlength(char* dest,unsigned long long l) {
  5. /* encoding is either l%128 or (0x80+number of bytes,bytes) */
  6. size_t needed=(sizeof l),i;
  7. if (l<128) {
  8. if (dest) *dest=l&0x7f;
  9. return 1;
  10. }
  11. for (i=1; i<needed; ++i)
  12. if (!(l>>(i*8)))
  13. break;
  14. if (dest) {
  15. size_t j=i;
  16. *dest=(char)(0x80+i); ++dest;
  17. while (j) {
  18. --j;
  19. *dest=(char)((l>>(j*8))&0xff);
  20. ++dest;
  21. }
  22. }
  23. return i+1;
  24. }
  25. #ifdef UNITTEST
  26. #include <assert.h>
  27. #include <string.h>
  28. int main() {
  29. char buf[100];
  30. #define zap() memset(buf,'_',sizeof buf)
  31. assert(fmt_asn1derlength(NULL,0)==1);
  32. zap(); assert(fmt_asn1derlength(buf,0)==1 && !memcmp(buf,"\x00_",2));
  33. assert(fmt_asn1derlength(NULL,0xc2)==2);
  34. zap(); assert(fmt_asn1derlength(buf,0xc2)==2 && !memcmp(buf,"\x81\xc2_",3));
  35. assert(fmt_asn1derlength(NULL,0x1234)==3);
  36. zap(); assert(fmt_asn1derlength(buf,0x1234)==3 && !memcmp(buf,"\x82\x12\x34_",3));
  37. return 0;
  38. }
  39. #endif