Understanding problem in bitwise operator in C

-7

Here x is any decimal number. What does this expression mean?

return ( (x & 0x0000FFFF)<<16 | (x & 0xFFFF0000)>>16 );
c
asked on Stack Overflow Aug 15, 2019 by Pranto Saha • edited Aug 15, 2019 by user694733

2 Answers

3

They are using bitwise operations to manipulate the variable x which is assumed to be of a type of 32 bits so probably an integer.

(x & 0x0000FFFF )<< 16 | (x & 0xFFFF0000) >> 16 

Lets break it down: (x & 0x0000FFFF) << 16 : will take the value of the last 2 bytes in X and bit shift them by 16 to the left which will effectively move the last 2 bytes in the expression x to the first 2 bytes.

(x & 0xFFFF0000) >> 16 : will do the exact opposite of the first and move the 2 first bytes to the place of the last 2 bytes.

In more detail: the (x & 0xFFFF0000 ) is resulting in a value of he first 2 bytes since the & operator will only match 1 to 1 and otherwise result in 0 on a bit level, since we have only ones on a bit level in the first 2 bytes in the expression 0xFFFF0000 we will get the value of the 2 first bytes. The shift operators will move the resulting value 16 steps to the left/right depending on the direction of the <> operators.

The | operator will merge the two expressions into a single value which is the x value where the 2 first bytes has become the 2 last and vice versa.

An example to clarify the actions.

x = 0x12345678
(x & 0x0000FFFF) // will result in 0x00005678
0x0000FFFF << 16  //will result in 0x56780000
// The other parenthesis is doing the exact same but opposite. Which will result in 0x00001234
The final part of the expression will look like this: 
0x56780000 | 0x00001234 // which will result in 0x56781234

More info on bitwise operators and their effects can be found here: https://fresh2refresh.com/c-programming/c-operators-expressions/c-bit-wise-operators/

answered on Stack Overflow Aug 15, 2019 by Mattemagikern • edited Aug 15, 2019 by Mattemagikern
1
uint32_t lo_16_bits = (x & 0x0000FFFF);
uint32_t hi_16_bits = (x & 0xFFFF0000);
uint32_t move_lo_bits_to_hi_bits = lo_16_bits << 16;
uint32_t move_hi_bits_to_lo_bits = hi_16_bits >> 16;
uint32_t recombined = move_lo_bits_to_hi_bits | move_hi_bits_to_lo_bits;

The code is simply swapping the lowest 16bits with the highest 16bits.

answered on Stack Overflow Aug 15, 2019 by robthebloke

User contributions licensed under CC BY-SA 3.0