I am trying to write some processor independent code to write some big endian files. I have an example code below and I can not understand why it does not work. All he has to do is let the byte store each byte of data one by one in a large trailing order. In my real program, I will then write a separate byte to the file, so I get the same byte order in the file, regardless of the 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, the byte always has a value of 0. This confuses me, I look at the debugger and see this:
data = 00010010001101000101011001111000 bitmask = 111111110000000000000000000000000000
I would think that the data and mask would give 00010010, but it just does byte 00000000 every time! How can he be? I wrote the code for a small serial number and it works fine, 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 work and the big endian not? Thanks for any help :-)
source share