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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Check if a HexaDecimal number is Even or Odd
- Convert a binary number to hexadecimal number
- Program to Convert Hexadecimal Number to Binary
- Largest Even and Odd N-digit numbers in Hexadecimal Number System
- Reverse a number using stack
- Reverse actual bits of the given number
- Reverse String according to the number of words
- Write a program to reverse digits of a number
- Find N numbers such that a number and its reverse are divisible by sum of its digits
- Write an Efficient C Program to Reverse Bits of a Number
- Program for decimal to hexadecimal conversion
- Program to Convert Octal to Hexadecimal
- Check the divisibility of Hexadecimal numbers
- Largest and Smallest N-digit Hexadecimal Numbers
- Program to convert KiloBytes to Bytes and Bits
- Find the count of natural Hexadecimal numbers of size N
- Reverse and Add Function
- PHP | Reverse a String
- Python list | reverse()
- Perl | Reverse an array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Akanksha_Rai