Okay, so I have a question, I guess about C strings. Below is my modification to some code (given in an answer to a previous stackoverflow question!), with the function call and the output. The function converts an input hex number (of length 8) to a binary number (of length 32).
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.
What am I doing wrong?
This line:
What do you think it does? Both arguments, before the asterisks are applied, refer to character arrays, or pointers to char. So when dereferenced, they refer to one char each. So this statement assigns the first char in binAddr equal to the first char in value, whereas presumably you wanted to return the whole string.