【问题标题】:Reading a Binary file and interpreting the data [closed]读取二进制文件并解释数据[关闭]
【发布时间】:2014-07-25 05:43:20
【问题描述】:

我的目标是从二进制文件中读取数据并最终将这些位存储在 32 位切片中。我发现了几种在 C++ 中读取二进制文件的不同方法,但不确定哪个是最佳选择,我的主要问题是,在存储数据后输出数据时,我没有访问单个位,而是显示 ASCII 字符。

int main(int argc, const char *argv[])
{

std::vector<char> memblock;
int i=0;
        ::std::ifstream in(argv[1], ::std::ios::binary);
        while (in) {
              char c;
              in.get(c);
              if (in) {
                 memblock.push_back(int(c));
                i++;
                  //::std::cout << "Read a " << int(c) << "\n";
              }
           }
std::cout << "The contents of memblock are:";
  for (std::vector<char>::iterator it = memblock.begin(); it != memblock.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';
return 0;
}

还有:

streampos size;
      char * memblock;

      ifstream file ("path", ios::in|ios::binary|ios::ate);
      if (file.is_open())
      {
        size = file.tellg();
        memblock = new char [size];
        file.seekg (0, ios::beg);
        file.read (memblock, size);
        file.close();

        cout << "the entire file content is in memory";

       for(int i =0; i<10; i++){
           cout << memblock[i+2000];
       }
      }

每种方法都有优势吗?还是有更好的方法?另外,如何确保存储二进制文件中的实际位值或二进制数据?谢谢

【问题讨论】:

标签: c++ binary ascii binaryfiles


【解决方案1】:

您想读取 32 位整数,而不是 char

uint32_t * memblock;
ifstream file ("path", ios::in|ios::binary|ios::ate);
   if (file.is_open())
   {
       size = file.tellg();
       memblock = new unit32_t [size / 4 + (size % 4 == 0 ? 0 : 1)];
       file.seekg (0, ios::beg);
       file.read (reinterpret_cast<char*>(memblock), size);
       file.close();

       cout << "the entire file content is in memory";

       for(int i =0; i<size/4; i++){
            cout << memblock[i];
       }
    }

【讨论】:

  • 没关系。但是分配语句还是有错别字。
  • 阅读时为什么要把memblock转换成char*?
  • @JohnSmith 因为ifstream::read 想要传入一个char 指针。
  • 注意:如果size不是4的倍数,则分配的内存不足。也许memblock = new unit32_t [(size + 3)/4];.
  • @chux 谢谢,固定答案
【解决方案2】:

正在阅读实际的二进制内容。通过cout 打印它会产生ascii 字符,因为cout 设计用于在传递char 值时打印字符串,除非另有说明。此外,如果您想将其存储在 32 位切片中,则不应使用 char 而是使用 32 位数据类型。试试uint32_t。然后不要忘记调整大小,因为文件大小以字节为单位,但uint32_t 有四个字节。

为了测试Nth 位(N 从 0 开始)是否设置在某个整数变量中,您可以定义以下宏:

#define IS_BIT_SET(v, N) ( (v) & ( 1<<(N) ) )
bool bit12Set = IS_BIT_SET(v, 12);

如果您需要更多舒适,请使用std::bitset

【讨论】:

  • 谢谢,那有没有办法直接打印位呢?还是一种访问单个位的方法?
  • 如果你想单独检查位,你必须使用位运算符和掩码。
猜你喜欢
  • 2018-03-23
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
  • 2014-06-29
  • 2012-11-26
  • 1970-01-01
相关资源
最近更新 更多