我正在将整数写入这样的文件:
for (int i = 0; i < 4; i++) {
writeInt8ToFile(126, ofst);
writeInt32ToFile(12500, ofst);
writeInt8ToFile(139, ofst);
}
(相关功能):void writeInt32ToFile(std::uint32_t i, std::fstream &fstr)
{
fstr.write(reinterpret_cast<char *>(&i), sizeof(std::uint32_t));
}
void writeInt8ToFile(std::uint8_t i, std::fstream &fstr)
{
fstr.write(reinterpret_cast<char *>(&i), sizeof(std::uint8_t));
}
然后,我还希望能够将这些字符转换回整数。我已经尝试过了:
(首先,将字节放入 vector )
std::vector<char> infs_bytes(
(std::istreambuf_iterator<char>(infs)),
(std::istreambuf_iterator<char>()));
(然后,将它们像这样转换回int):// Iterate through all bytes
for (int i = 0; i < btVec.size() / MAP_BYTE_SIZE; i++) {
// Integers
std::uint8_t i1;
std::uint32_t i2;
std::uint8_t i3;
char buf[] = {btVec[i+1], btVec[i+2], btVec[i+3], btVec[i+4]}; // Middle 4 bytes
// memcpy all bytes to their corresponding integer types
std::memcpy(&i1, &btVec[i], 1); // First byte
std::memcpy(&i2, buf, 4);
std::memcpy(&i3, &btVec[i+5], 1); // Last byte
std::cout << (int)i1 << std::endl;
std::cout << i2 << std::endl;
std::cout << (int)i3 << std::endl;
}
但是,当我尝试输出到上一片段中所示的stdout时,将输出以下内容:126
139
212
126
48
212
0
48
显然,这不是我写入文件的内容。预期的输出是126
12500
139
126
12500
139
126
12500
139
126
12500
139
最佳答案
你的循环
for (int i = 0; i < btVec.size() / MAP_BYTE_SIZE; i++) {
是错的。您必须移动每个块MAP_BYTE_SIZE
元素的起始位置,而不是1。尝试
for (int j = 0; j < btVec.size() / MAP_BYTE_SIZE; j++) {
int i = j * MAP_BYTE_SIZE;
关于c++ - 将uint32_ts和uint_8ts写入char文件,然后将它们转换回uint32_ts和uint_8ts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63237805/