简体   繁体   English

从二进制文件读取uint8_t

[英]Reading uint8_t from binary file

I have a file where are binary numbers and I have to read them. 我有一个文件,其中有二进制数,我必须阅读它们。 I use: 我用:

ifstream data("date.txt", ios_base::binary);

int count_16 = 0; //count how many uint16_s I have already read
uint16_t numbers_16; // Allocate storage for uint16_s
int count_8 = 0;
uint8_t numbers_8;
int count_char = 0;
char name[20];

data.seekg(0U, ios_base::beg); // Move the input position indicator to the beginning of the file for reading
data.read(reinterpret_cast<char*>(&numbers_16), sizeof(uint16_t)); // into numbers_16
cout << numbers_16; 
count_16++;

data.seekg(count_16 * sizeof(uint16_t) + count_8 * sizeof(uint8_t) + count_char * sizeof(name+1));
data.read(reinterpret_cast<char*>(&numbers_16), sizeof(numbers_16)); // Read the element into number
cout << numbers_16 << endl;
count_16++;

everything works untill that: 一切正常,直到:

data.seekg(count_16 * sizeof(uint16_t) + count_8 * sizeof(uint8_t) + count_char * sizeof(name+1));
data.read(reinterpret_cast<char*>(&numbers_8), sizeof(numbers_8)); // Read the element into number
cout << numbers_8 << endl;
count_8++;

And here I don't get any number or anything readable. 在这里,我没有任何数字或可读性。 I don't know why this method works for uint16_t but not for uint8_t. 我不知道为什么该方法适用于uint16_t但不适用于uint8_t。 Can someone explain why it is wrong and how to read uint8_t from file? 有人可以解释为什么这是错误的,以及如何从文件中读取uint8_t吗?

It turned out it is good why of reading. 事实证明,阅读为什么很好。 The only mistake was here: 唯一的错误是在这里:

cout << numbers_8 << endl;

I just wrote (int) before numbers_8 and now it looks fine. 我只是在number_8之前写了(int),现在看起来还不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM