Reverse bytes of a Hexadecimal Number
Given an unsigned integer N. The task is to reverse all bytes of N without using a temporary variable and print the reversed number.
Input: N = 0xaabbccdd
Input: N = 0xa912cbd4
The naive approach is to extract the appropriate byte is to use mask(&) with shift operators.
#define REV(x) ( ((x&0xff000000)>>24) | (((x&0x00ff0000)<<8)>>16) | (((x&0x0000ff00)>>8)<<16) |
((x&0x000000ff) << 24) )
The idea is to use shift operators only.
- Move the position of the last byte to the first byte using left shift operator(<<).
- Move the position of the first byte to the last byte using right shift operator(>>).
- Move the middle bytes using the combination of left shift and right shift operator.
- Apply logical OR (|) to the output of all the above expression, to get the desired output.
Below is the implementation of the above approach :
a912cbd4 is reversed to d4cb12a9
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.