4

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))
nav_jan
  • 2,473
  • 4
  • 24
  • 42
manish sardiwal
  • 126
  • 1
  • 2
  • 8
  • 1
    So did u achieve what you wanted ? – KARTHIK BHAT Jan 10 '14 at 07:10
  • 1
    Is this problem really different from reversing an integer ? – nav_jan Jan 10 '14 at 07:11
  • 1
    What is the question? I can see problems with that approach only when `sizeof(X) > 4` or when X is signed. – Aki Suihkonen Jan 10 '14 at 07:11
  • Can you give us some constraints on the solution? Is this for a hex number of arbitrary length? Is it input as a string, or do you have it as an integer? I think your question has been asked before, and an excellent answer is given : http://stackoverflow.com/a/2182184/1967396 – Floris Jan 10 '14 at 07:30
  • There is no constraints on the solution. I just want to reverse bytes of a 32 bit integer. Input is integer and output is also a integer. – manish sardiwal Jan 13 '14 at 04:26
  • Yeah i achieved but is there any more simple solution for it? – manish sardiwal Jan 13 '14 at 04:26
  • If you know the hardware you are on, there are assembler instructions that will do this very quickly. See for example http://stackoverflow.com/a/19370831/1967396 – Floris Jan 13 '14 at 04:50

2 Answers2

2

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.

Floris
  • 45,857
  • 6
  • 70
  • 122
0

check this #

  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

KARTHIK BHAT
  • 1,410
  • 13
  • 23