2

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?

momonkey7
  • 23
  • 4
  • A string has no "most significant byte". And if that is supposed to be an integer: it seem to only have 4 bytes. It is not clear what you mean. See [ask], provide a [mcve]. And search for "c operators", if that is not too much asked. – too honest for this site Sep 30 '16 at 00:15
  • 2
    See [Bit Twiddling Hacks](http://graphics.stanford.edu/~seander/bithacks.html). You need to rotate 4 high-order bytes while leaving the low-ones unchanged (though with the value AAAA in the low-order bytes, it will be hard to spot mishandled changes that preserve byte values; use `0xDEAD0123` or something else with distinct bytes in the low-order part of the value. Also, you seem to be mixing up bytes with nybbles; each hex digit is a nybble (aka nibble), and it appears you want to deal with the 4 most significant nybbles, not bytes. – Jonathan Leffler Sep 30 '16 at 00:18
  • It's an unsigned integer not a string. I'm just representing it in hexadecimal for readability. – momonkey7 Sep 30 '16 at 00:18
  • Ah you're right yes nibbles not bytes then. Because a nibble is 4 binary digits correct? And a byte is 8? – momonkey7 Sep 30 '16 at 00:28
  • Yes; a nybble is 4 bits and a byte is 8 bits on most systems these days. (The exceptions are few and far between and I've never programmed on any of them.) – Jonathan Leffler Sep 30 '16 at 00:34
  • See also [Best practices for circular shift rotate operations](http://stackoverflow.com/questions/776508/best-practices-for-circular-shift-rotate-operations-in-c) and [Near constant time rotate that doesn't violate the standards](http://stackoverflow.com/questions/31387778/near-constant-time-rotate-that-does-not-violate-the-standards). – Jonathan Leffler Sep 30 '16 at 00:39

1 Answers1

3

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)

user253751
  • 57,427
  • 7
  • 48
  • 90