我在将 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;
}
最佳答案
在这种情况下:
unsigned int test_3 = 0xc3;
常量0xc3
的类型为int
。它的值 (195) 位于 int
的正范围内,因此当它通过赋值转换为 unsigned int
时,它会保留该值。
对于本例:
unsigned int test_4 = (char)(0xc3);
该值首先被转换为char
。假设 char
是 8 位,并且 2 的补码表示用于负数,则该表示落入负数范围 (-61)。因此,当转换为更大的类型时,添加的额外位将被设置为 1,以保留相同的负值。
关于c - 将 char 转换为 int 时出现意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42814890/