I am trying to clear the first nibble in a 16-bit unsigned integer (set it to 0).
One of the approaches I attempted was to use left bit shifting and then right bit shifting to clear the first four bits.
Here is my program.
#include <stdio.h>
#include <stdint.h>
int main() {
uint16_t x = 0xabcd; // I want to print out "bcd"
uint16_t a = (x << 4) >> 4;
printf("After clearing first four bits: %x\n", a);
return 0;
}
I am expecting the first bit shift (x << 4)
to evaluate to 0xbcd0
and then the right bit shift to push a leading 0
in front - 0x0bcd
. However, the actual output is 0xabcd
.
What confuses me more is if I try to use the same approach to clear the last four bits,
uint16_t a = (x >> 4) << 4;
it works fine and I get expected output: abc0
.
Why, in the program above, does the right bit shifting not push a leading 0?
Happens due to integer promotion. On systems where int
is larger than 16 bits, your expression is converted to
uint16_t a = (int)((int)x << 4) >> 4;
and the upper bits are not stripped therefore.
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