[英]char type bitwise operation fails in to int
I am try to bitwise operate in C. Here is my code: 我尝试在C中按位操作。这是我的代码:
int main() {
char c = 127;
c <<= 1;
if (c == 0xfe) {
printf("yes");
}
else {
printf("No");
}
return 0;
}
System console print No. What I expect to receive is Yes. 系统控制台打印否。我希望收到的是是。 the value in c after bit moving is ffffffffe.
位移后c中的值为ffffffffe。 It seems that system has changed 8bits to a 32bits.
似乎系统已经将8位改为32位。 Can anyone help me.
谁能帮我。
You have correctly figured out the content of the lower byte, ie 0xfe
. 您已正确计算出低位字节的内容,即
0xfe
。 However, there is more to what's actually happening here: when you write 然而,在这里发生的事情还有更多:当你写作时
if (c == 0xfe) {
...
}
you are comparing c
, a char
, to an int
constant 0xfe
. 你正在将
c
,一个char
与一个int
常量0xfe
。 In this situation C rules require promoting char c
to int
for comparison. 在这种情况下,C规则要求将
char c
提升为int
以进行比较。 Since char
is signed on your platform, 0xfe
gets promoted to 0xfffffffe
, which is why the comparison subsequently fails. 由于
char
在您的平台上签名,因此0xfe
被提升为0xfffffffe
,这就是比较随后失败的原因。
If you want to do the comparison in char
type, cast 0xfe
to char
, like this: 如果你想在
char
类型中进行比较, 0xfe
为char
,如下所示:
if (c == (char)0xfe) {
...
}
Unsigned characters, on the other hand, would give you no trouble with int
promotion, because they fit nicely in an int
: 另一方面,无符号字符会给你
int
促销带来麻烦,因为它们非常适合int
:
unsigned char c = 127;
c<<=1;
if (c == 0xfe) { // No casting is necessary
...
}
Note: The behavior of c <<= 1
is implementation-defined due to char
overflow. 注意:由于
char
溢出, c <<= 1
的行为是实现定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.