[英]c and bit shifting in a char
I am new to C and having a hard time understanding why the code below prints out ffffffff
when binary 1111111
should equal hex ff
. 我是C语言的新手,很难理解为什么当二进制
1111111
应该等于十六进制ff
时,以下代码会输出ffffffff
。
int i;
char num[8] = "11111111";
unsigned char result = 0;
for ( i = 0; i < 8; ++i )
result |= (num[i] == '1') << (7 - i);
}
printf("%X", bytedata);
You print bytedata
which may be uninitialized. 您打印可能未初始化的
bytedata
。
Replace 更换
printf("%X", bytedata);
with 同
printf("%X", result);
Your code then run's fine. 您的代码然后运行正常。 code
码
Although it is legal in C, for good practice you should make 尽管在C语言中是合法的,但为了良好作法,您应该
char num[8] = "11111111";
to 至
char num[9] = "11111111";
because in C the null character ('\\0') always appended to the string literal. 因为在C语言中,空字符('\\ 0')始终附加在字符串文字之后。 And also it would not compile as a C++ file with g++.
而且它也不会与g ++一起编译为C ++文件。
EDIT 编辑
To answer your question 回答你的问题
If I use char the result is FFFFFFFF but if I use unsigned char the result is FF.
如果使用char,则结果为FFFFFFFF,但如果使用unsigned char,则结果为FF。
Answer: 回答:
Case 1: In C size of char is 1byte(Most implementation). 情况1:在C中char的大小为1byte(大多数实现)。 If it is unsigned we can use 8bit and hold maximum
11111111
in binary and FF
in hex(decimal 255). 如果它是无符号的,我们可以使用8位,最大二进制数为
11111111
,十六进制数为FF
(十进制255)。 When you print it with printf("%X", result);
用
printf("%X", result);
打印时printf("%X", result);
, this value implicitly converted to unsigned int which becomes FF
in hex. ,此值隐式转换为unsigned int,十六进制变为
FF
。
Case 2: But when you use char(signed), then MSB bit use as sign bit, so you can use at most 7 bit for your number whose range -128 to 127 in decimal. 情况2:但是当您使用char(signed)时,MSB位用作符号位,因此您最多可以将7位用于其数字,其范围为-128到127(十进制)。 When you assign it with
FF
(255 in decimal) then Integer Overflow occur which leads to Undefined behavior . 当您为它分配
FF
(十进制255)时,会发生Integer Overflow ,从而导致Undefined behavior 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.