Reverse the order of bytes

Hello everyone. This is my first post in the forum. I am Italian, so forgive any spelling errors.

I need to write to file (in binary mode) an integer (so 4 bytes) in this order, for example:

int x = 4125;

When I read the file with a hex editor, I will then read: 00 00 10 1D.

How can I do?

Thank you.
Last edited on
If you already know how to write bytes to a file, then you only have to put them in a byte array like this:
1
2
3
4
5
6
unsigned char bytes[4];
//      4125 = 0x0000101D
bytes[0] = x & 0xFF000000; //Contains the big byte (0x00)
bytes[1] = x & 0x00FF0000;
bytes[2] = x & 0x0000FF00;
bytes[3] = x & 0x000000FF; //Contains the little byte (0x1D) 
Last edited on
Thanks. I tried this:

1
2
3
4
unsigned long int Endian_DWord_Conversion(unsigned long int dword)
 {
   return ((dword>>24)&0x000000FF) | ((dword>>8)&0x0000FF00) | ((dword<<8)&0x00FF0000) | ((dword<<24)&0xFF000000);
}


And it works!
Last edited on
@magnificence7
You forgot to right-shift the appropriate amount.
1
2
3
4
5
6
unsigned char bytes[4];
int x = 0x0000101D;
bytes[0] = (x >> 24) & 0xFF;
bytes[1] = (x >> 16) & 0xFF;
bytes[2] = (x >>  8) & 0xFF;
bytes[3] =  x        & 0xFF;


@GliderKite
Reading and writing binary data is a common issue, and byte order is important.
Have you seen my post here?
http://www.cplusplus.com/forum/beginner/11431/#msg53963

Also, converting between endians and byte-order reversing are common operations. A set of functions available on any computer are the htonl(), ntohl(), htons(), and ntohs() networking functions. Using them requires linking with your platform's networking faciliites. If you don't want to do that, it is easy enough to roll your own, as you did. (Good job!)

Hope this helps.
Thanks Duoas.

Ps: interesting post.
Last edited on
Topic archived. No new replies allowed.