## Monday, 27 September 2010

### Reverse 32-bit Hexadecimal Value (with C)

A 32-bit hexadecimal value such as 0xABCD1234 may need to be reversed as 0x4321DCBA. This might be needed. The following is a naive implementation of reversing a hexadecimal. It would be interesting quiz for undgrad CS student to write a n-bit version of this.

signed int reverse_hex(signed int num) {
/* stupid reverse hex */
int rev= 0x00000000;
int digit= 0x00000000;

digit=num << 28;
rev=num << 20;
rev=digit+rev;
digit=(num << 12) & mask2;
rev=digit+rev;
digit=(num << 4) & mask3;
rev=digit+rev;
digit=(num >> 4) & mask4;
rev=digit+rev;
digit=(num >> 12) & mask5;
rev=digit+rev;
digit=(num >> 20) & mask6;
rev=digit+rev;
digit=(num >> 28) & mask7;
rev=digit+rev;
return(rev);
}

However, the above procedure is not so usual while it is reversed by chunks of 4-bit. More realistic situation is reversing from between big and little endian representation. Such as, 0xABCD1234 would be reversed as 0x3412CDAB, so byte ordering matters. The following is the C function doing this. Similarly n-byte version of
this function will be left as a further exercise.

signed int reverse_hex_byte(signed int num) {
/* stupid reverse hex */
int rev= 0x00000000;
int digit= 0x00000000;

/* Move 1st byte */
digit=num >> 24;
/* Move 2nd byte */
digit= num >>8;
rev=digit+rev;
/* Move 3rd byte */
digit= num <<8 br="br"> digit=digit & mask3;
rev=digit+rev;
/* Move 4rd byte */
digit= num <<24 br="br"> digit=digit & mask4;
rev=digit+rev;
return(rev);
}