I am try to bitwise operate in C. Here is my code:
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. It seems that system has changed 8bits to a 32bits. Can anyone help me.
You have correctly figured out the content of the lower byte, i.e. 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
. In this situation C rules require promoting char c
to int
for comparison. Since char
is signed on your platform, 0xfe
gets promoted to 0xfffffffe
, which is why the comparison subsequently fails.
If you want to do the comparison in char
type, cast 0xfe
to char
, like this:
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
:
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.