将文件中的字节转换为整数 C++

Convert bytes from a file to an integer c++

我正在尝试用这段代码解析一个 .dat 文件,逐字节读取它。(文件名在 arv[1] 中)

   std::ifstream is (arv[1], std::ifstream::binary);
      if (is) {

        is.seekg (0, is.end);
        int length = is.tellg();
        is.seekg (0, is.beg);

        char * buffer = new char [length];

        is.read (buffer,length);

        if (is)
          std::cout << "all characters read successfully.";
        else
          std::cout << "error: only " << is.gcount() << " could be read";
        is.close();
    }

现在所有文件都在 buffer 变量中。该文件包含以 32 位表示的数字,我如何遍历缓冲区一次读取 4 个字节并将它们转换为整数?

而不是:

char * buffer = new char [length];
is.read (buffer,length);

您可以使用:

int numIntegers = length/sizeof(int);
int* buffer = new int[numIntegers];
is.read(reinterpret_cast<char*>(buffer), numIntegers*sizeof(int));

更新,回应OP的评论

我没有发现我建议的方法有任何问题。这是一个示例程序和我使用 g++ 4.9.2 看到的输出。

#include <iostream>
#include <fstream>
#include <cstdlib>

void writeData(char const* filename, int n)
{
   std::ofstream out(filename, std::ios::binary);
   for ( int i = 0; i < n; ++i )
   {
      int num = std::rand();
      out.write(reinterpret_cast<char*>(&num), sizeof(int));
   }
}

void readData(char const* filename)
{
   std::ifstream is(filename, std::ifstream::binary);
   if (is)
   {
      is.seekg (0, is.end);
      int length = is.tellg();
      is.seekg (0, is.beg);

      int numIntegers = length/sizeof(int);
      int* buffer = new int [numIntegers];
      std::cout << "Number of integers: " << numIntegers << std::endl;

      is.read(reinterpret_cast<char*>(buffer), numIntegers*sizeof(int));

      if (is)
         std::cout << "all characters read successfully." << std::endl;
      else
         std::cout << "error: only " << is.gcount() << " could be read" << std::endl;
      for (int i = 0; i < numIntegers; ++i )
      {
         std::cout << buffer[i] << std::endl;
      }
   }
}

int main()
{
   writeData("test.bin", 10);
   readData("test.bin");
}

输出

Number of integers: 10
all characters read successfully.
1481765933
1085377743
1270216262
1191391529
812669700
553475508
445349752
1344887256
730417256
1812158119

首先,您有内存泄漏,您动态分配字符数组但从未删除[]它们。 使用 std::string 代替:

std::string buffer(length,0);
is.read (&buffer[0],length);

现在,假设您已正确写入整数,并将其正确读入缓冲区,您可以使用此字符数组作为指向整数的指针:

int myInt = *(int*)&buffer[0];

(你明白为什么吗?) 如果您存储了一个以上的整数:

std::vector<int> integers;
for (int i=0;i<buffer.size();i+=sizeof(int)){
 integers.push_back(*(int*)&buffer[i]);
}