所以我正在编写一个非常小而简单的程序,它将一个数字作为输入,将其转换为十六进制,然后一次打印出两个字符。
对于某些数字,它会在输出前打印出 ffffff。
这是我的代码:
//Convert the input to an unsigned int
unsigned int a = strtoul (argv[1], NULL, 0);
//Convert the unsigned int to a char pointer
char* c = (char*) &a;
//Print out the char two at a time
for(int i = 0; i < 4; i++){
printf("%02x ", c[i]);
}
Run Code Online (Sandbox Code Playgroud)
大多数输出都很好,看起来像这样:
./hex_int 1
01 00 00 00
Run Code Online (Sandbox Code Playgroud)
但是对于某些数字,输出如下所示:
./hex_int 100000
ffffffa0 ffffff86 01 00
Run Code Online (Sandbox Code Playgroud)
如果您删除所有 f,则转换是正确的,但我无法弄清楚为什么它仅在某些输入上执行此操作。
谁有想法?
您的参数和打印格式不匹配。默认参数提升会导致您的char参数 ( c[i]) 被提升为int,其符号扩展(显然您char是有符号类型)。然后您告诉printf将该参数解释为unsigned int使用%x格式。Boom - 未定义的行为。
用:
printf("%02x ", (unsigned int)(unsigned char)c[i]);
Run Code Online (Sandbox Code Playgroud)
反而。