How to shift bits correctly in C ++?

I have a 0x8F hexadecimal number (10001111 in binary). I want to change this value, so the new one will be 0xC7 (11000111). I tried:

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

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

+6
source share
3 answers

A right shift on an unsigned quantity will lead to the introduction of new zeros , and not to them.

Note that shifting to the right is not a proper rotation . For this you need

 x = (x >> 1) | (x << 7) 
+14
source

This is because you want to "rotate right" rather than "rotate right." Therefore, you need to adjust the minimum β€œdrop out” bit:

  x = ((x & 1) << CHAR_BITS-1) | (x >> 1); 

gotta do the trick.

[And at least some compilers will detect this particular set of operations and convert to the corresponding ror or rol statement]

+8
source

An offset to the right or left will be filled with 0 respectively, to the left or right of the byte. After the switch, you need an OR with the correct value to get what you expect.

 x = (x >> 1); /* this is now 01000111 */ x = x | ( 0x80 ); /* now we get what we want */ 

Here I am OR ing with a byte of 10000000 , which is 0x80 , which leads to 0xC7 .

Having made it shorter, it will be as follows:

 x = (x >> 1) | (unsigned char)0x80; 
+2
source

Source: https://habr.com/ru/post/981482/


All Articles