0

Possible Duplicate:
Hex to char array in C

For example if I want a hexadecimal number like this "F32FC0F5EC894E16" I would store it in an unsigned char variable like this:

unsigned char s[8] = {0xF3, 0x2F, 0xC0, 0xF5, 0xEC, 0x89, 0x4E, 0x16};

But If I am getting this in a string which has this number:

char a[16]="F32FC0F5EC894E16"

How do I convert it into hexadecimal number and use it in a similar way as the variable 's' above?

Community
  • 1
  • 1
maddy2012
  • 153
  • 1
  • 3
  • 15

2 Answers2

2

There is an overflow in this assignment:

char a[16]="F32FC0F5EC894E16"

You didn't leave room for the null terminator. Char arrays do not have to be null terminated, but strings are, and that is a string declaration. Don't declare char array sizes for variables initialized with hardcoded values, use [].

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void hexString2byteStream (char *in, unsigned char *out, int len) {
    char *p = in;
    char byte[3] = { 0 };
    int i = 0;

    while (sscanf(p, "%2s", byte)) {
        out[i++] = strtoul(byte, NULL, 16);
        if (i == len) break;
        p += 2;
    }
}

int main(void) {
    char a[]="F32FC0F5EC894E16";
    unsigned char bs[8];
    int i;

    hexString2byteStream(a, bs, sizeof(bs));

    for (i = 0; i < 8; i++) {
        printf("%x\n", bs[i]);
    }

    return 0;
}

Notice that out is not a null terminated string.

CodeClown42
  • 11,194
  • 1
  • 32
  • 67
0

If the number of hex digits is always an even number, and the string is uppercased, then the algorithm is easy. Caution, there are no controls for exceptions nor errors. This is only a basic algorithm.

void hexCharsToBinary ( char* a, int length, char* s)
{
    int i;
    for( i=0; i< length; i++)
    {
        char mask    = (i&1)? 0xf0 : 0x0f ;
        char charVal = ((*(a+i)>='0'&&*(a+i)<='9')?*(a+i)-'0':*(a+i)-'A'+10) ;

        s[i>>1] = (s[i>>1]&mask) | charVal << ((i&1)?0:4) ;
    }

 }
Gabriel
  • 3,319
  • 1
  • 16
  • 21
  • You should enter code-obfuscation contests... "then the algorithm is easy..." **EDIT** Why the check for `*(a+i)<='8'`, and not `<=9`? – Yuri May 16 '12 at 07:15
  • @Yuri, yes it was an error. I have edited the code. – Gabriel May 16 '12 at 08:22