Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does compound bit shifting not set leading nibble to 0? [duplicate]

Tags:

c

bit-shift

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?

like image 611
letsgofeminism Avatar asked May 02 '19 22:05

letsgofeminism


1 Answers

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.

like image 67
ensc Avatar answered Sep 19 '22 22:09

ensc