簡體   English   中英

將字節從文件轉換為整數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個字節的緩沖區並將其轉換為整數?

首先,存在內存泄漏,您動態分配了字符數組,但從未刪除[]它們。 使用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]);
}

代替:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM