C print hex bytes

对着背影说爱祢 提交于 2020-05-02 04:22:48

问题


I have code in a C program with hex data which I want to iterate over, for example to print out each of the hex bytes:

char input[] = "\x31\xd2\xb2\x30";
for (int i = 0; i < strlen(input); i++) {
    printf("%02X\n", input[i]);
}

However, the output is not what I expect, for example the above prints:

31
FFFFFFD2
FFFFFFB2
30

I also tried to cast the output as an (unsigned int), however I receive the same output.

Can somebody point out the issue with this simple script?


回答1:


The arguments passed to printf are sign extended unless you cast them to an unsigned type like this:

printf("%02X\n", (unsigned char)input[i]);



回答2:


printf("%02X") expects an unsigned integer; Passing a negative value of type char (and 0xD2 of type char is a negative value) will lead to promote the negative char value to a 32 bit unsigned int, thereby filling up the leading bits with 1 and yielding 0xFFFFFFD2in the end. This is then printed.

To overcome this, you could "tell" printf to take the value provided as an 8 bit value:

printf("%02hhX\n", input[i]) 

Another option would be to declare input as unsigned char, because then 0xD2 would not be considered "negative", and promotion to 32 bit would work as expected:

unsigned char input[] = "\x31\xd2\xb2\x30";

Note that then strlen would require to cast the input, i.e. strlen((char*)intput).




回答3:


char input[] must be unsigned char input[]. That's how you store binary bytes.




回答4:


// You can use like this  

char input[] = "\x31\xd2\xb2\x30";

for (int i = 0; i < strlen(input); i++) {  
    printf("%02X\n", input[i] & 0xff);  
}  

Output: 
31  
D2  
B2  
30  

it will mask out the upper bits and keep only the lower 8 bits.



来源:https://stackoverflow.com/questions/46145173/c-print-hex-bytes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!