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?

6
  • 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 How to Ask, provide a minimal reproducible example. And search for "c operators", if that is not too much asked. Commented Sep 30, 2016 at 0:15
  • 2
    See Bit Twiddling Hacks. 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. Commented Sep 30, 2016 at 0:18
  • It's an unsigned integer not a string. I'm just representing it in hexadecimal for readability. Commented Sep 30, 2016 at 0:18
  • Ah you're right yes nibbles not bytes then. Because a nibble is 4 binary digits correct? And a byte is 8? Commented Sep 30, 2016 at 0: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.) Commented Sep 30, 2016 at 0:34

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.