C++:解析 132x65 二进制文件
C++: parsing a 132x65 binary file
所以这是我必须/必须做的。我有一个.txt文件,它的大图是 132x72。我需要做的是将其放入十六进制值的 c 数组中。
我需要找到一种方法来抓取前 8 行的第一个字符并将它们水平组合在一起,以便我可以将它们转换为十六进制。然后我需要向下做 9 次。
例:
00000
00000
11111
01010
10101
10101
01010
10101
我需要变成:
00101101
00110010
00101101
00110010
00101101
最好/最简单的方法是什么?老实说,我不知道从哪里开始。
假设 1 和 0 是.txt文件中的字符(如果是二进制内容,那么您需要先转换它们):只需将文件逐行读取到数组中即可。然后,您可以大步打印阵列,即首次打印字符 0, 8, 16, 24 ...然后是 1、9、17、...等等:
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%c", chars[i + j * ROWS]);
}
printf("n");
}
类似的东西。
这是一个有趣的格式。无论如何,在一行中读取,然后将值适当地添加到数组中。这就是我的意思:
输入行 1:01101
将对应于某个数组:image[0][0] = 0, image[1][0] = 1 ...
这最好通过使用push_back()
方法std::vector
来完成。
// If you know the image size already
unsigned char image[NUM_ROWS][NUM_COLS/8]; // 8 bits per byte
std::ifstream file("yourfile.txt", std::ifstream::in);
// Initialize the array to 0 with memset or similar
// Read the whole file
int rows = 0;
int cols = 0;
while(!file.eof) {
std::string line;
// Get line by line
std::getline(file, line);
// Parse each line (probably better in another function)
const char* str = line.c_str();
while(str[rows] != ' ') {
unsigned val = str[rows] - '0'; // Convert to int
unsigned shift = 8 - (rows % 8); // 8 bits per byte - this is tricky big-endian or little endian?
image[rows][cols/8] |= val << shift; // Convert to int val and pack it to proper position
rows++;
}
cols++;
rows = 0;
}
file.close();
该代码未经测试,但应该可以让您大致了解如何正确读取数据。现在,您有一个格式正确的二维数组,其中包含您的值(这就是移位的目的)。从这里,您可以将这些值作为int
值并适当地转换它们(以 16 为基数的转换与二进制相比是微不足道的 - 即每个字节有两个十六进制数字)
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 编译多个C++文件.调用二进制文件以运行代码
- 如何使用位字段将数据从二进制文件复制到结构中?
- uint8_t同一二进制文件的不同十进制值
- C++单个生成文件多个二进制文件
- 尝试将数字写入二进制文件时引发异常
- C++中读/写二进制文件
- 如何忽略某些二进制文件的执行?
- 对在不同二进制文件中创建的对象文件的依赖关系
- C++:解析 132x65 二进制文件