-
June 22nd, 2004, 11:11 PM
#1
Reverse byte order using union, How?
Hello !
Now, I am able to get reverse byte order using the following function:
Code:
void GetReverseHexa(int n) {
int a, b, c, d, e;
a = n & 0x000000FF;
b = n & 0x0000FF00;
c = n & 0x00FF0000;
d = n & 0xFF000000;
a <<= 24;
b <<= 8;
c >>= 8;
d >>=24;
e = a|b|c|d;
printf("\nReverse byte order: %2x\n\n",e);
}
parameter n is the given number (user input). Now, the task it to come up with the same output but using union. Anyone who has an idea?
-
June 23rd, 2004, 01:12 AM
#2
Code:
union Word
{
DWORD dword;
struct
{
BYTE lo_byte_short0;
BYTE hi_byte_short0;
BYTE lo_byte_short1;
BYTE hi_byte_short1;
} bytes;
};
Word Reverse(Word& w)
{
Word result;
result.bytes.lo_byte_short0 = w.bytes.hi_byte_short1;
result.bytes.hi_byte_short0 = w.bytes.lo_byte_short1;
result.bytes.lo_byte_short1 = w.bytes.hi_byte_short0;
result.bytes.hi_byte_short1 = w.bytes.lo_byte_short0;
return result;
}
int main()
{
Word a;
a.dword = 0x12345678;
printf("\nReverse byte order: %2x\n\n", Reverse(a).dword);
return 0;
}
-
June 23rd, 2004, 01:31 AM
#3
Ok, I got the answer I want. Now, I want to share the code here
Code:
void GetReverseByteOrder(int n) {
union {
int nGiven;
unsigned char val[4];
} HEXA;
HEXA.nGiven = n; /* n is input of user */
for (int i=0; i<4; i++)
printf("%02x",HEXA.val[i]);
}
What does this piece of code do?
-- user types in a number, say 123456
-- 123456 is stored to n and passed to HEXA.nGiven
-- we know that 123456 is 1E240 in base 16
-- now, we wanted to reverse 1E240 making it 40E20100
-- 40E20100 is generated by the code above
How come? Can u imagine how? :-)
That's it! A generous man from codeguru shared the above code. I just did a little modification. I forgot his username here in this forum but anyway, many many thanks to him!
-
June 23rd, 2004, 01:33 AM
#4
Kheun,
Thank you for your reply.
Anyway, I found a shorter code though I do not know if the one I found is good to use. What do you think?
Anyway, how does your code differs to the code I got?
-
June 23rd, 2004, 01:44 AM
#5
Well, both are doing almost the same thing except that your code only displays in reverse order without the actual reversing of the int.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|