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;
int mask1=0x0f000000;
int mask2=0x00f00000;
int mask3=0x000f0000;
int mask4=0x0000f000;
int mask5=0x00000f00;
int mask6=0x000000f0;
int mask7=0x0000000f;

digit=num << 28;
rev=num << 20;
rev=rev & mask1;
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;
int mask1=0x000000ff;
int mask2=0x0000ff00;
int mask3=0x00ff0000;
int mask4=0xff000000;

/* Move 1st byte */
digit=num >> 24;
rev=digit & mask1;
/* Move 2nd byte */
digit= num >>8;
digit=digit & mask2;
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);
}


(c) Copyright 2008-2024 Mehmet Suzen (suzen at acm dot org)

Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License