Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to right shift bits in c++?

Tags:

c++

bit-shift

I have a hex number 0x8F (10001111 in binary). I want to right shift that value, so the new one would be 0xC7 (11000111). I tried with:

unsigned char x = 0x8F;
x=x>>1; 

but instead of 0xC7 I got 0x47? Any ideas on how to do this?

like image 714
osemec Avatar asked Jan 24 '15 10:01

osemec


1 Answers

Right shift on an unsigned quantity will make new zeros to enter, not ones.

Note that right shift is not a right rotation. To do that you need

x = (x >> 1) | (x << 7)
like image 85
6502 Avatar answered Oct 14 '22 07:10

6502