Reverse bytes of a Hexadecimal Number
Last Updated :
16 Mar, 2023
Given an unsigned integer N. The task is to reverse all bytes of N without using a temporary variable and print the reversed number.
Examples:
Input: N = 0xaabbccdd
Output: 0xddccbbaa
Input: N = 0xa912cbd4
Output: 0xd4cb12a9
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) )
Efficient approach: 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 :
C
#include <stdio.h>
#define REV(n) ((n << 24) | (((n>>16)<<24)>>16) | (((n<<16)>>24)<<16) | (n>>24))
int main()
{ unsigned int n = 0xa912cbd4;
printf ( "%x is reversed to %x" , n, REV(n));
return 0; }
|
C++
#include <iostream>
using namespace std;
int REV( int n)
{
return ((n >> 24) & 0xff) | ((n << 8) & 0xff0000)
| ((n >> 8) & 0xff00) | ((n << 24) & 0xff000000);
}
int main()
{
int n = 0xa912cbd4;
cout << hex << n << " is reversed to " << REV(n)
<< endl;
return 0;
}
|
Java
class GFG {
public static int REV( int n)
{
return ((n >> 24 ) & 0xff )
|
((n << 8 ) & 0xff0000 )
|
((n >> 8 ) & 0xff00 )
|
((n << 24 ) & 0xff000000 );
}
public static void main(String[] args)
{
int n = 0xa912cbd4 ;
System.out.println(Integer.toHexString(n) + " is reversed to " + Integer.toHexString(REV(n)));
}
}
|
C#
using System;
class GFG {
public static ulong REV( uint n)
{
return ( ulong )((n >> 24) & 0xff)
|
( ulong )((n << 8) & 0xff0000)
|
( ulong )((n >> 8) & 0xff00)
|
( ulong )((n << 24)
& 0xff000000);
}
public static void Main( string [] args)
{
uint n = 0xa912cbd4;
Console.WriteLine(n.ToString( "X" )
+ " is reversed to "
+ REV(n).ToString( "X" ));
}
}
|
Python3
def REV(n: int ) - > int :
return ((n >> 24 ) & 0xff ) | ((n << 8 ) & 0xff0000 ) | ((n >> 8 ) & 0xff00 ) | ((n << 24 ) & 0xff000000 )
if __name__ = = '__main__' :
n = 0xa912cbd4
print (f "{n:x} is reversed to {REV(n):x}" )
|
Javascript
function REV(n) {
return (BigInt(n) >> 24n & 0xffn)
|
(BigInt(n) << 8n & 0xff0000n)
|
(BigInt(n) >> 8n & 0xff00n)
|
(BigInt(n) << 24n & 0xff000000n);
}
const n = 0xa912cbd4;
console.log(n.toString(16)
+ " is reversed to "
+ REV(n).toString(16));
|
Output:
a912cbd4 is reversed to d4cb12a9
Time complexity: O(1)
Auxiliary space: O(1)
Share your thoughts in the comments
Please Login to comment...