gpt4 book ai didi

c++ - 从二进制文件读取 uint8_t

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:35 29 4
gpt4 key购买 nike

我有一个文件,其中包含二进制数,我必须读取它们。我使用:

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++;

一切正常,直到:

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++;

在这里我没有得到任何数字或任何可读的内容。我不知道为什么这个方法适用于 uint16_t 但不适用于 uint8_t。有人可以解释为什么它是错误的以及如何从文件中读取 uint8_t 吗?

最佳答案

事实证明,读书是有好处的。唯一的错误在这里:

cout << numbers_8 << endl;

我刚刚在 numbers_8 之前写了 (int),现在看起来不错。

关于c++ - 从二进制文件读取 uint8_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49301060/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com