Honneamise
Honneamise

Reputation: 60

Correct way to concatenate bitwise operations?

Im in need to concatenate some bitwise operations but the current output seems to be wrong. The splitted operations are similar to this :

unsigned char a = 0x12
unsigned char x = 0x00;
x = a << 4;
x = x >> 4;

expected result x = 0x02; current result x = 0x02;

If i try to concatenate the operations the result is not correct:

unsigned char a = 0x12
unsigned char x = 0x00;
x = (a << 4) >> 4;

expected result x = 0x02; current result x = 0x12;

Thanks in advance for any suggestion.

Upvotes: 2

Views: 345

Answers (2)

Martin Morterol
Martin Morterol

Reputation: 2870

The problem is (a << 4) is cast to int (via Integral promotion), so (0x12 << 4) >> 4 is essentially 0x12

What you want to do is convert back (a << 4) to unsigned char by using static_cast

The final code:

   unsigned char a = 0x12;
   unsigned char x = 0x00;
   x = static_cast<unsigned char>(a << 4) >> 4;   

Upvotes: 7

Gardener
Gardener

Reputation: 2660

Compiler is NOT applying integral promotions for the >> and << operations

You might think that

x = (a << 4) >> 4;

Would use a byte-wide register for the operation, but the compiler promotes the char a to an int before doing the shift, preserving the bits that are shifted to the left.

You can solve this by doing this:

x = ((a << 4) & 0xff) >> 4;

Again, the issue is that integral promotion preserves the bits until the final cast.

Upvotes: 2

Related Questions