how do you reverse and rotate hex numbers and return the number in C with bitwise operators?
for example:
0xabcd -> 0xdcba
0xabcd -> 0xdabc
how do you reverse and rotate hex numbers and return the number in C with bitwise operators?
for example:
0xabcd -> 0xdcba
0xabcd -> 0xdabc
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
.
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.