momonkey7 momonkey7 - 3 months ago 13
C Question

C how to roll bytes

This is just something I wanted to do for fun, no real practical use of it.

Say for example I enter 0xDEADAAAA

I want to be able to transform the value into 0xDDEAAAAA

Meaning the 4 most significant bytes shift over one byte.
And the 4th most significant byte now becomes the first most significant byte.

Kind of like a circular shift of the first 4 bytes.

For now I'm doing

value = value >> ((sizeof(unsigned int) * 8) / 2);

This will shift all bytes over one byte.
But how would I do the circular roll of the 4th most significant byte into the MSB?


You can split the number into three parts and process them separately, then combine them.

The part that is unchanged is value & 0x0000FFFF.
The part that you want to shift right 4 bits is value & 0xFFF00000.
The part that you want to shift left 12 bits is value & 0x000F0000.

So do all of those things, then combine the results with |:

value =  (value & 0x0000FFFF)
      | ((value & 0x000F0000) << 12)
      | ((value & 0xFFF00000) >> 4);

(note, here I've lined up all the masks so it's easy to see, but obviously you don't have to do that)