【发布时间】:2017-03-15 16:00:50
【问题描述】:
我在将char 转换为unsigned int 时遇到意外行为。有时剩余的位用 0 填充,有时用 1 填充。
在 gcc 4.9.2 上测试的一个简单程序
unsigned int test_1 = 0x01;
unsigned int test_2 = (char)(0x01);
unsigned int test_3 = 0xc3;
unsigned int test_4 = (char)(0xc3);
输出是
00000000 00000000 00000000 00000001
00000000 00000000 00000000 00000001
00000000 00000000 00000000 11000011
11111111 11111111 11111111 11000011
我希望“空白”位填充 0 而不是 1。
预期输出:
00000000 00000000 00000000 00000001
00000000 00000000 00000000 00000001
00000000 00000000 00000000 11000011
00000000 00000000 00000000 11000011
完整代码如下:
#include "stdio.h"
#define binary_p( x ) printBits(sizeof(x),&x)
void printBits(size_t const size, void const * const ptr)
{
unsigned char *b = (unsigned char*) ptr;
unsigned char byte;
int i, j;
for (i=size-1;i>=0;i--)
{
for (j=7;j>=0;j--)
{
byte = (b[i] >> j) & 1;
printf("%u", byte);
}
printf(" ");
}
puts("");
}
int main(int argc, char *argv[])
{
unsigned int test_1 = 0x01;
unsigned int test_2 = (char) (0x01);
unsigned int test_3 = 0xc3;
unsigned int test_4 = (char) (0xc3);
binary_p(test_1);
binary_p(test_2);
binary_p(test_3);
binary_p(test_4);
return 0;
}
【问题讨论】:
-
c/c++是 UB.. -
改用
(unsigned char)!结果是一样的吗? -
你的编译器根据标准做了正确的事情,但显然不是你想要的。你想发生什么?
-
您期望什么行为以及为什么?
-
似乎
char是签名的,而到unsigned int的转换是签名扩展的。如果您转换为带符号的int,您应该看到int和char的负值相同。您可以改用unsigned char,正如 Iharob 上面建议的那样。
标签: c type-conversion