将字节从文件转换为整数c ++

时间:2015-07-17 14:00:51

标签: c++ parsing byte

我正在尝试使用此代码解析一个.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个字节并将它们转换为整数?

2 个答案:

答案 0 :(得分:1)

首先,你有内存泄漏,你动态分配字符数组但从不删除它们。 改为使用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]);
}

答案 1 :(得分:0)

而不是:

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