简体   繁体   English

在 cpp 中读取二进制文件有问题吗?

[英]Problem with reading a binary file in cpp?

I have a binary file called "input.bin" where every character is of 4 bits.我有一个名为“input.bin”的二进制文件,其中每个字符都是 4 位。 The file contains this kind of data:该文件包含此类数据:

0f00 0004 0018 0000 a040 420f 0016 030b
0000 8000 0000 0000 0000 0004 0018 0000

where 0f is the first byte.其中 0f 是第一个字节。

I want to read this data and to do that, I am using the following code:我想读取这些数据并这样做,我使用以下代码:

#include <string>
#include <iostream>
#include <fstream>

int main()
{
      char buffer[100];
      std::ifstream myFile ("input.bin", std::ios::in | std::ios::binary);
      myFile.read (buffer, 100);

      if (!myFile.read (buffer, 100)) {
        std::cout << "Could not open the required file\n";
      }
      else
      {
        for (int i = 0; i < 4; i++)
        {
          std::cout << "buffer[" << i << "] = " << static_cast<unsigned>(buffer[i]) << std::endl;
        }
        myFile.close();
      }
    return 0;
}

Currently I am printing just four bytes of data, and when I run it, I get this output:目前我只打印四个字节的数据,当我运行它时,我得到这个 output:

buffer[0] = 0
buffer[1] = 24
buffer[2] = 0
buffer[3] = 0

Why is it not printing the value of 0f and just printing the value of 18 in index 1 whereas it is actually at index 6?为什么它不打印 0f 的值,而只在索引 1 中打印 18 的值,而实际上它在索引 6 处?

The problem is here问题就在这里

myFile.read (buffer, 100);

if (!myFile.read (buffer, 100)) {

where you read twice, and thus ignore the first 100 bytes (if there are more than 100 of them).你读了两次,因此忽略了前 100 个字节(如果它们超过 100 个)。

Remove the first read , or change the condition to if (!myFile)删除第一个read ,或将条件更改为if (!myFile)

You print the contents of the data as characters .您将数据的内容打印为字符 And none of the first four bytes are really printable characters.前四个字节都不是真正可打印的字符。

You need to print them as (unsigned) integers:您需要将它们打印为(无符号)整数:

// Unsigned bytes to avoid possible sign extensions in conversions
unsigned char buffer[100];

...

// Convert the bytes to unsigned int for printing their numerical values
std::cout << "buffer[" << i << "] = " << static_cast<unsigned>(buffer[i]) << '\n';

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

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