I have this code:
unsigned char *command = "0000";
unsigned char foo = (hex_char_to_int(command[0]) << 4) | hex_char_to_int(command[1]);
unsigned char bar = (hex_char_to_int(command[2]) << 4) | hex_char_to_int(command[3]);
printf("foo: %02x, bar: %02x\r\n", foo, bar);
It uses this function:
unsigned char hex_char_to_int(unsigned char ch) {
switch (ch){
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'A': return 0xA;
case 'B': return 0xB;
case 'C': return 0xC;
case 'D': return 0xD;
case 'E': return 0xE;
case 'F': return 0xF;
case 'a': return 0xA;
case 'b': return 0xB;
case 'c': return 0xC;
case 'd': return 0xD;
case 'e': return 0xE;
case 'f': return 0xF;
default: return 0;
}
}
This is the result:
"JW\xd6\x96'$$LK\x90\xbbar: 3030\r\r\n"
This is on the Keil C51 compiler, on an AT89C55WD, with printf()
going over a serial port.
What is going on?
EDIT
I change the printf line to
printf("%02x%02x\r\n", (unsigned int)foo, (unsigned int)bar);
So it looks like a bug in printf
. Please, programmers, never make a debugging tool that lies. I beg you.