Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big Endian and Little Endian for Files in C++

I am trying to write some processor independent code to write some files in big endian. I have a sample of code below and I can't understand why it doesn't work. All it is supposed to do is let byte store each byte of data one by one in big endian order. In my actual program I would then write the individual byte out to a file, so I get the same byte order in the file regardless of processor architecture.

#include <iostream>

int main (int argc, char * const argv[]) {
 long data = 0x12345678;
 long bitmask = (0xFF << (sizeof(long) - 1) * 8);
 char byte = 0;

    for(long i = 0; i < sizeof(long); i++) {
  byte = data & bitmask;
  data <<= 8;
 }
    return 0;
}

For some reason byte always has the value of 0. This confuses me, I am looking at the debugger and see this:

data = 00010010001101000101011001111000 bitmask = 11111111000000000000000000000000

I would think that data & mask would give 00010010, but it just makes byte 00000000 every time! How can his be? I have written some code for the little endian order and this works great, see below:

#include <iostream>

int main (int argc, char * const argv[]) {
 long data = 0x12345678;
 long bitmask = 0xFF;
 char byte = 0;

    for(long i = 0; i < sizeof(long); i++) {
  byte = data & bitmask;
  data >>= 8;
 }
    return 0;
}

Why does the little endian one work and the big endian not? Thanks for any help :-)

like image 693
orgazoid Avatar asked Dec 29 '22 03:12

orgazoid


1 Answers

You should use the standard functions ntohl() and kin for this. They operate on explicit sized variables (i.e. uint16_t and uin32_t) rather than compiler-specific long, which necessary for portability.

Some platforms provide 64-bit versions in <endian.h>

like image 90
Will Avatar answered Dec 31 '22 16:12

Will