c++ - 将uint32_ts和uint_8ts写入char文件,然后将它们转换回uint32_ts和uint_8ts

标签 c++ binary int memcpy

我正在将整数写入这样的文件:

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/

相关文章:

c++ - 32 位二进制到 24 位有符号转换

python - 在 Python 中的二进制数中添加下划线作为分隔符

c# - 我如何着手将时间变成公共(public)整数?

ios - Swift 中的数组不计算对象

c++ - Rand 在从最大为 75 的数字 (36) 开始时如何工作

c++ - 如何编写一个以 boost::Range 作为参数的函数?

c++ - 为什么这个字符串到整数的转换函数要减1?

c++11 按值捕获 lambda 产生错误的值

c++ - 将整个二进制文件读入缓冲区,然后以特定格式解析它

c - 向 int 字符串添加前缀