[英]Binary file read different results for amount of bytes read at a time
我正在從文件中讀取二進制數據,但是一次讀取一個字節會產生預期的結果,而一次讀取一個以上的字節則不會。 一次讀取一個:
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
正在正確讀取文件。 在系統上, uint16_t
是little-endian,即,低8位存儲在第一個字節中,高8位存儲在第二個字節中,因此從文件中讀取的第一個字節成為該位集的低8位(位0-7),第二個字節變為高8位(8-15位)。 打印位集時,從位15到位0依次打印位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.