printf char 为 c 中的十六进制 [英] printf char as hex in c
问题描述
我希望从下面的代码输出类似 \9b\d9\c0...
的东西,但我得到 \ffffff9b\ffffffd9\ffffffc0\ffffff9d\53\ffffffa9\fffffff4\49\ffffffb0\ffffffeff\ffffffd9\ffffffaa\61\fffffff7\54\ffffffb
.我向 char 添加了显式转换,但它没有效果.这是怎么回事?
I expect ouput something like \9b\d9\c0...
from code below, but I'm getting \ffffff9b\ffffffd9\ffffffc0\ffffff9d\53\ffffffa9\fffffff4\49\ffffffb0\ffff
ffef\ffffffd9\ffffffaa\61\fffffff7\54\fffffffb
. I added explicit casting to char, but it has no effect. What's going on here?
typdef struct PT {
// ... omitted
char GUID[16];
} PT;
PT *pt;
// ... omitted
int i;
for(i=0;i<16;i++) {
printf("\\%02x", (char) pt->GUID[i]);
}
只转换为 (unsigned char)
对我有用.编译器在使用 %02hhx
(gcc -Wall
) 时向我发出警告.(unsigned int)
没有效果.
only casting to (unsigned char)
worked for me. Compiler spits warnings on me when using %02hhx
(gcc -Wall
). (unsigned int)
had no effect.
推荐答案
发生这种情况的原因是您系统上的 char
已签名.当您将它们传递给具有可变数量参数的函数时,例如 printf
(在签名的固定参数部分之外)char
将转换为 int
,它们在这个过程中得到了符号扩展.
The reason why this is happening is that char
s on your system are signed. When you pass them to functions with variable number of arguments, such as printf
(outside of fixed-argument portion of the signature) char
s get converted to int
, and they get sign-extended in the process.
要解决此问题,请将值强制转换为 unsigned char
:
To fix this, cast the value to unsigned char
:
printf("\\%02hhx", (unsigned char) pt->GUID[i]);
这篇关于printf char 为 c 中的十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!