automated

hex2bin preserving endianness in C

I cannot help copying this snippet. Assume f is a (char *) of length L, containing an hex string like '0aabdda' (without the leading “0x”, like something coming from a sha function —or like the sha1 stored by Leopard in the password files, which is the origin of this problem). You want to transform it into the corresponding sequence of bytes (that is, assuming the string is of even length, otherwise, we add a trailing, yes, trailing, at the end, ‘0’). We shall store the result in t, which points to a (char *) of length L/2.

The following C code does the trick: (first of all we must set t to 0);

int k = (L%2 ? L/2+1 : L/2);
memset(t, 0, L/2);
for(i=0; i<L; i++){
  t[i/2] += ((i%2) ? 1 : 16) *
    ((f[i] > 'F') ? (f[i] - 'a' + 10) :
      ((f[i] > '9') ? (f[i] - 'A' + 10) :
        (f[i] - '0'))) 
}

Thus, if f points to the string 100aff, t points to the sequence of bytes 16, 10, 255 after the loop.

The reverse operation is well known:

for(i=0; i<k; i++){
  sprintf(f+2*i, "%02X", t[i]);
}

I just don’t want to forget it.

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*Required Fields