I noticed some strange behavior with bitshifting with brackets
#include <stdio.h>
int main(void)
{
unsigned char c;
unsigned char d;
c = 153;
c = (c << 7) >> 7;
printf("%d\n", c);
d = 153;
d = (d << 7);
d = (d >> 7);
printf("%d\n", d);
}
output:
153
1
I expected c
to also have a value of 1... whats going on? Is this undefined?
Bit-shifting a char
automatically promotes it to an int
. This is why a left shift of 7 bits doesn't chop anything off.
Source: section 6.5.7 of the C standard
The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With