3

Possible Duplicate:
Convert a long hex string in to int array with sscanf

I have seen some topics on this before, but most solutions are in Python (curse you for being so easy!).

Is there an easy way to do this in C? This is what my solution needs to be in. I know it's not complicated conceptually, but I am horrendous with C string manipulation and address handling.

Thanks for the help, guys!

----------EDIT-------------

Okay, so I solved that problem, and I have another question (I didn't want to open up a new thread!). Below is my modification to the given code, with the function call and the output.

void htoi(const char *ptr, char *binAddr) {
char value[32] = "";
char ch = *ptr;
int i;
const char* quads[] = {"0000", "0001", "0010", "0011", "0100", "0101",
                     "0110", "0111", "1000", "1001", "1010", "1011",
                     "1100", "1101", "1110", "1111"};

while (ch == ' ' || ch == '\t')
    ch = *(++ptr);

for (i = 0; i < 8; i++) {
    if (ch >= '0' && ch <= '9')
        strncat(value, quads[ch - '0'], 4);
    if (ch >= 'A' && ch <= 'F')
        strncat(value, quads[10 + ch - 'A'], 4);
    if (ch >= 'a' && ch <= 'f')
        strncat(value, quads[10 + ch - 'a'], 4);

    ch = *(++ptr);
    printf("%s\n", value);
}

*binAddr = *value;
}

Here is my function call:

char line[11], hexAddr[8], binAddr[32];
htoi(hexAddr, binAddr);
printf("%s\n", binAddr);

Here is the output (when input with 001133c0):

0000

00000000

000000000001

0000000000010001

00000000000100010011

000000000001000100110011

0000000000010001001100111100

00000000000100010011001111000000

0���

The last line (with the special characters) is the printf(binAddr) in the main function above. It is clear from the printf statements inside the function that the binary code is being constructed correctly.

Once again, this comes down to me not being worth anything with address manipulation. What am I doing wrong?

Community
  • 1
  • 1
Jojo Jonas
  • 225
  • 2
  • 4
  • 15
  • 4
    Not to be a jerk, but no one here is probably going to code this for you. This is a great opportunity for you to become less "horrendous with C string manipulation and address handling". Give it a shot and ask questions. – linuxuser27 Nov 20 '11 at 22:34

1 Answers1

3

It's fairly easy with a lookup table:

const char * const quads = { "0000", "0001", "0010", .... };

const char * hex_to_bin_quad(unsigned char c)
{
  if (c >= '0' && c <= '9') return quads[     c - '0'];
  if (c >= 'A' && c <= 'F') return quads[10 + c - 'A'];
  if (c >= 'a' && c <= 'f') return quads[10 + c - 'a'];
  return -1;
}

Now iterate over your string and append hex_to_bin_quad(c) for each character (e.g. using strncat). You already know that you'll need a target string of length 4 * strlen(src) + 1, so allocate, iterate and concatenate.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084