C++:解析 132x65 二进制文件

C++: parsing a 132x65 binary file

本文关键字:二进制文件 132x65 解析 C++      更新时间:2023-10-16

所以这是我必须/必须做的。我有一个.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 为基数的转换与二进制相比是微不足道的 - 即每个字节有两个十六进制数字)