2012-09-29 49 views
0

我目前正在处理与排序相关的问题。二进制阅读,reinterpret_cast和排序

假设我在big-endian系统中有一个big-endian文件。

在此文件中的第一个值是2882400152 = 0xABCDEF98是一个整数4.

要在整数4,_myint4阅读价值,我简单地做:

mystream.read(reinterpret_cast<char*>(&_myint4), sizeof(_myint4)) 

的问题是:是什么相当于读取文件中的整数4值,整数8,_myint8

  • 为大端文件和系统?
  • 为小端文件和系统?

我的第一个猜测是类似的东西:

mystream.read((reinterpret_cast<char*>(&_myint8))+4, 4); // big-endian file/system 
mystream.read(reinterpret_cast<char*>(&_myint8), 4); // little-endian file/system 

但我不知道的。有什么好办法做到这一点?

重要提示:我不能使用临时整数4的值,我需要直接读取_myint8中的整数4。

+1

解释限制将不胜感激,人们会认为它是与嵌入式硬件相关的东西。 –

+0

你的例子对我来说很好。 –

+1

P.S.确保在读入之前将'_myint8'设置为零。 –

回答

0

你的猜测似乎是正确的:

_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 

要弄清楚你自己的字节顺序,它可能会帮助在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' 

那么,你是对的,你只需要以确保你在内存中的位置不占优势。