summaryrefslogtreecommitdiffstats
path: root/fmt_asn1length.c
blob: 3df929b52fa6da8c1033494715b08344fdfc1135 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include "asn1.h"

/* write int in least amount of bytes, return number of bytes */
/* as used in ASN.1 length */
size_t fmt_asn1length(char* dest,size_t l) {
  /* encoding is either l%128 or (0x80+number of bytes,bytes) */
  size_t needed=(sizeof l),i;
  if (l<128) {
    if (dest) *dest=l&0x7f;
    return 1;
  }
  for (i=1; i<needed; ++i)
    if (!(l>>(i*8)))
      break;
  if (dest) {
    int j=i;
    *dest=0x80+i; ++dest;
    while (j) {
      --j;
      *dest=((l>>(j*8))&0xff);
      ++dest;
    }
  }
  return i+1;
}