Reputation: 60341
I'm currently dealing with endianness-related problems.
Let's assume that I have a big-endian file in a big-endian system.
The first value in this file is 2882400152 = 0xABCDEF98
which is an integer 4.
To read that value in an integer 4, _myint4
, I simply do :
mystream.read(reinterpret_cast<char*>(&_myint4), sizeof(_myint4))
The question is : what is the equivalent to read the integer 4 value in the file, in an integer 8, _myint8
?
My first guess would be something like that :
mystream.read((reinterpret_cast<char*>(&_myint8))+4, 4); // big-endian file/system
mystream.read(reinterpret_cast<char*>(&_myint8), 4); // little-endian file/system
But I'm not sure at all. What is the good way to do this ?
IMPORTANT : I cannot use a temporary integer 4 value, I need to read directly the integer 4 in _myint8
.
Upvotes: 1
Views: 3476
Reputation: 24110
Your guess seems right:
_myint8 = 0;
mystream.read((reinterpret_cast<char*>(&_myint8))+4, 4); // big-endian file/system
mystream.read(reinterpret_cast<char*>(&_myint8), 4); // little-endian file/system
To figure out byte ordering on your own, it might help to play a bit in Python:
>>> import struct
>>> struct.pack(">Q", 0xabcdef98) // Big-endian 8-byte int.
'\x00\x00\x00\x00\xab\xcd\xef\x98' // Its layout in memory.
>>> struct.pack(">I", 0xabcdef98) // Big-endian 4-byte int.
'\xab\xcd\xef\x98'
>>> struct.pack("<Q", 0xabcdef98) // Little-endian 8-byte int.
'\x98\xef\xcd\xab\x00\x00\x00\x00'
>>> struct.pack("<I", 0xabcdef98) // Little-endian 4-byte int.
'\x98\xef\xcd\xab'
So you are right, you just need to ensure you have zeroes in the places in memory that you aren't overriding.
Upvotes: 2