views:

211

answers:

2

how do you reverse and rotate hex numbers and return the number in C with bitwise operators?

for example:

0xabcd -> 0xdcba

0xabcd -> 0xdabc
+11  A: 

It's hard to know where to begin with this question. Plus I smell homework.

Some points:

  • There is no such thing as a "hex number". Hex is just a notation. How do you reverse and rotate decimal numbers and return the number in C? For example:

    1776 -> 6771

    1776 -> 6771?

  • To solve this problem, you need a deep understanding of positional notation, whether it's base 10, base 16, base 2, or what have you.

  • All you need can be had by adding, subtracting, multiplying, and dividing. Those are operations on numbers. Modulus is also very helpful.

  • If you happen to want to multiply or divide by a power of two, I commend to you the C left shift << and right shift >> operators. These work perfectly for numbers that are represented using the C types unsigned or unsigned long.

Norman Ramsey
+1 for explaining (in an appropriately cursory fashion) the distinction between the *number* and its notation in a particular *base*.
Adam Robinson
Really? I get annoyed when people assume you don't know the definition. Just because you used a word that is semantically wrong does not mean you don't know what it is.
Louis
@Louis: I don't think that Norman is implying that he doesn't know what it is, I think he's trying to make the distinction more clear. The fact that "10" in decimal is "A" in hex but they're the SAME, and so "switching" the number 123 in hex is going to be a mathematically different operation than switching 123 in decimal is not immediately obvious to most people.
Adam Robinson
Oh yeah I wasn't talking about this particular case. I just find in general that a lot of responses end up being definitions if you used a wrong term.
Louis
A: 

To swap the number using bit operations:

Do a bitwise AND operation using the original number with appropriate mask to extract a hex digit (4 bits) from the original number.

Shift this extracted bit pattern to it's new location.

Bitwise OR the repositioned bit patterns together.

Hope this helps.

Dave L Delaney