2017-06-14 59 views
1

我正在讀取文件中的二進制數據,但是一次讀取一個字節給出預期結果,而一次讀取不止一個字節不會。讀一次一個:二進制文件讀取一次讀取的字節數的不同結果

void readFile(){ 
     std::ifstream in; 
     in.open("file.bin", std::ios:binary); 

     uint8_t byte1; 
     uint8_t byte2; 
     in.read(reinterpret_cast<char *>(&byte1), sizeof(byte1)); 
     in.read(reinterpret_cast<char *>(&byte2), sizeof(byte2)); 

     std::cout << std::bitset<8>(byte1) << std::bitset<8>(byte2); 
} 

由此產生的

0000101000000110 

一次讀取兩個預期輸出:

void readFile(){ 
     std::ifstream in; 
     in.open("file.bin", std::ios:binary); 

     uint16_t twobytes; 
     in.read(reinterpret_cast<char *>(&twobytes), sizeof(twobytes)); 

     std::cout << std::bitset<16>(twobytes); 
} 

可生產意想不到的輸出

0000011000001010 

回答

4

正在讀取文件correctl年。在您的系統uint16_t是little-endian,即低8位存儲在第一個字節和高8位存儲在第二個字節,所以從文件讀取的第一個字節成爲位集的低8位(位0-7),第二個字節變成高8位(8-15位)。當打印位集時,按順序打印位,從位15到位0.

+0

哦,當然!交換endianness導致我需要的輸出。謝謝! – MalusPuer