[英]C++ binary files not read correctly
我正在閱讀一個文件,該文件是在 C++ 中的小端英特爾處理器上以高端方式編寫的。 該文件是用二進制編寫的通用文件。 我曾嘗試使用 open() 和 fopen() 閱讀它,但他們似乎都犯了同樣的錯誤。 該文件是用於訓練來自 MNIST 數據集的圖像的二進制文件。 它包含 4 個標頭,每個標頭大小為 32 位,並以高位序存儲。 我的代碼正在運行,只是沒有為第二個標題提供正確的值。 它適用於其余的標題。 我什至在十六進制編輯器中打開了該文件,以查看該值是否可能是錯誤的,但它是正確的。 由於某種奇怪的原因,該程序只讀取了第二個標頭的值錯誤:這是處理僅讀取標頭的代碼:
void DataHandler::readInputData(std::string path){
uint32_t headers[4];
char bytes[4];
std::ifstream file;
//I tried both open() and fopen() as seen below
file.open(path.c_str(), std::ios::binary | std::ios::in);
//FILE* f = fopen(path.c_str(), "rb");
if (file)
{
int i = 0;
while (i < 4)//4 headers
{
//if (fread(bytes, sizeof(bytes), 1, f))
//{
// headers[i] = format(bytes);
// ++i;
//}
file.read(bytes, sizeof(bytes));
headers[i++] = format(bytes);
}
printf("Done getting images file header.\n");
printf("magic: 0x%08x\n", headers[0]);
printf("nImages: 0x%08x\n", headers[1]);//THIS IS THE ONE THAT IS GETTING READ WRONG
printf("rows: 0x%08x\n", headers[2]);
printf("cols: 0x%08x\n", headers[3]);
exit(1);
//reading rest of the file code here
}
else
{
printf("Invalid Input File Path\n");
exit(1);
}
}
//converts high endian to little indian (required for Intel Processors)
uint32_t DataHandler::format(const char * bytes) const
{
return (uint32_t)((bytes[0] << 24) |
(bytes[1] << 16) |
(bytes[2] << 8) |
(bytes[3]));
}
我得到的輸出是:
Done getting images file header.
magic: 0x00000803
nImages: 0xffffea60
rows: 0x0000001c
cols: 0x0000001c
nImages 應該是 60,000 或 (0000ea60)h 的十六進制,但它正在讀取它作為 ffff ......出於某種原因。 這是在十六進制編輯器中打開的文件: 正如我們所看到的,第二個 32 位數字是 0000ea60 但它讀錯了......
似乎char
在您的環境中已簽名,因此數據中的0xEA
被符號擴展為0xFFFFFFEA
。 這將打破較高的數字。
為了防止這種情況,您應該使用unsigned char
而不是char
。 (對於bytes
的元素類型和format()
的參數)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.