如何诊断保存和加载位向量(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));
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 函数何时会在c++中包含stack_Unwind_Resume调用
- Python中的for循环与C++有何不同
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 当简单捕获中的标识符显示为参数的声明符 ID 时,没有编译器诊断
- 在C++中释放内存期间,迭代器与指针有何不同
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 如何使用CAPL的诊断功能获取CAN传输的数据(256字节)?
- 在 std::index_sequence 中没有诊断包膨胀
- #pragma(*诊断)当将Clang分析器与GCC编译器混合时
- 类中的 C++ int 被设置为值,似乎不知从何而来
- -fvisibility-inline-hidden 与 gcc 中的 -fvisibility=hidden 有何不同
- GCC 编译器是否应该对涉及 [[fallthrough]] 属性的格式错误的C++代码进行诊断?
- 如何显式调用运算符<<
- 收益率和回报有何不同?
- 覆盖私有功能,它与受保护功能有何不同?
- 擦除删除成语的性能增益从何而来
- 使用类/函数模板组合进行意外诊断