繁体   English   中英

如何诊断保存和加载位向量(std :: vector的奇怪行为 <bool> )?

[英]How to diagnose bizarre behavior of saving and loading a bit vector (std::vector<bool>)?

我正在编写一个一次性实用程序来编辑游戏的单色位图格式。 8x8单色精灵有0x10000个“插槽”。 我将每个8x8子画面存储在八个字节中,每个字节代表开或关像素的水平线。

当我在插槽0到24中绘制字符A到Y时,一切都很好。它们都以完全相同的位模式经历了一次保存和加载的往返过程。 但是随后,在插槽25中的Z绘图在往返过程中丢失了其水平线之一。 更糟糕的是,这会发生 Z所在的任何位置,并将其下方的所有行向上移动! 我注意到25后插槽中的其他模式具有其他类似的行为。

我的代码看起来像一次只能检查单个像素,因此我对如何诊断此问题一无所知。

据我所知,问题是删除0x0C字节。 ASCII换页符( ^L'\\f' )字符似乎不太可能出现问题。

我没有找到任何关于缺少换页符的Google结果,因此我猜测这是我的代码中的错误。

这是保护程序和加载程序。 (这不是我编写发布或生产代码的方式!😳)

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <SDL.h>
#include <stdint.h>

static std::vector<bool> bitmap(0x400000, 0);

void save(const char *path)
{
    std::ofstream f(path, std::ios::binary);
    for (int i = 0; i < 0x10000; ++i)
    for (int j = 0; j < 8; ++j) {
        uint8_t byte = 0;
        for (int k = 0; k < 8; ++k)
            byte |= bitmap[8 * (8 * i + j) + k] << (7 - k);
        f << byte;
    }
    f.close();
    std::cout << "Wrote charmap to " << path << std::endl;
}

void load(const char *path)
{
    std::ifstream f(path, std::ios::binary);
    for (int i = 0; i < 0x10000; ++i)
    for (int j = 0; j < 8; ++j) {
        uint8_t byte;
        f >> byte;
        for (int k = 0; k < 8; ++k)
            bitmap[8 * (8 * i + j) + k] = !!(byte & (1 << (7 - k)));
    }
    f.close();
    std::cout << "Read charmap from " << path << std::endl;
}

int main(int argc, char *argv[]) { /* ... snip ... */ }

我希望保留0x0C字节,但是将其删除。 感谢您的指导!

处理二进制文件时,即使以二进制模式打开它们,也不要使用格式化流运算符( f << ...;f >> ...; )。 您不需要格式化的输入/输出,而是希望按原样写入/读取字节。 改用ofstream::write()ifstream::read()方法,例如:

//f << byte;
f.write(reinterpret_cast<char*>(&byte), sizeof(byte));
//f >> byte;
f.read(reinterpret_cast<char*>(&byte), sizeof(byte));

暂无
暂无

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

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