I want to reverse the bytes of hexadecimal number like:
0x08090a0b
should convert to 0x0b0a0908
.
I have used this macro.
#define REV(X) ((X << 24) | (((X>>16)<<24)>>16) | (((X<<16)>>24)<<16) | (X>>24))
I want to reverse the bytes of hexadecimal number like:
0x08090a0b
should convert to 0x0b0a0908
.
I have used this macro.
#define REV(X) ((X << 24) | (((X>>16)<<24)>>16) | (((X<<16)>>24)<<16) | (X>>24))
It is cleaner and easier to follow if you combine shifting with masking: below I show both the complete expression, and its components separately. Note that you don't need the leading zeros in the mask - I put it there for clarity / alignment. And you don't need masks for the first and last term, as all the "unwanted" bits shift out of the expression.
#define REV(X) ((X << 24) | (( X & 0xff00 ) << 8) | (( X >> 8) & 0xff00 ) | ( X >> 24 ))
One byte at a time:
#define R1(X) ((X & 0x000000ff ) << 24 )
#define R2(X) ((X & 0x0000ff00 ) << 8 )
#define R3(X) ((X & 0x00ff0000 ) >> 8 )
#define R4(X) ((X & 0xff000000 ) >> 24 )
To print out the number correctly, use
printf("%08x", REV(x));
This will make sure that leading zeros are printed. You have to make sure that your input is a 32 bit unsigned integer for this to work correctly.
int main(void)
{
// your code goes here
unsigned int X = 0x08090a0b;
printf("%8x", ((X << 24) | (((X>>16)<<24)>>16) | (((X<<16)>>24)<<16) | (X>>24)));
return 0;
}
Your output is correct only. are you saying that 0 initially is not being displayed ??
09 = 9 in your case x0b0a0908 = b0a0908