Logical right shift in C with ~0 value

  • A+

I have a very simple code, in which logical shift works with ~0 value in strange way

As I know its related to the signed/unsigned data types

#include <stdio.h>  void printfbits(int x) {     for (int i=7; i>=0;i--) {         printf("%d", x>>i & 1);     }     printf("/n"); }  int main() {     printfbits(~0>>1);  } 

I expect 0111111, not 1111111. I also tried, no success

printfbits(((unsigned int)~0)>>1); 


In most platforms, int is 32-bit or 64-bit long. Therefore, you are shifting more than 8 bits to the right, which leaves you with more than 8 bits enabled:

11...11111111 >> 1 


11...11111111 // if sign extension happens 01...11111111 // if not 

As you see, regardless of whether sign extension happens or not, you will still see all 1s since you only print the lower 8 bits.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: