从二进制文件 c++ 读取 16 位整数

Reading 16-bit integers from binary file c++

本文关键字:整数 读取 二进制文件 c++      更新时间:2023-10-16

我不确定我是否做对了,所以我想检查我的代码。 它有效,但我不确定它是否正常工作。我需要它来读取二进制文件,并将 16 位整数存储在所需的确切大小的整数数组中。我试图做sizeof(storage[i])这样我就可以看看我是否存储了 16 位,但它说 32(我猜是因为 int 自动分配 4 个字节?

        void q1run(question q){
        int end;
        std::string input = q.programInput;
        std::ifstream inputFile (input.c_str(), ios::in | ios::binary);                     //Open File
        if(inputFile.good()){                                       //Make sure file is open before trying to work with it
                                                                    //Begin Working with information
           cout << "In File:  t" << input << endl;
           inputFile.seekg(0,ios::end);
           end=inputFile.tellg();
           int numberOfInts=end/2;
           int storage[numberOfInts];
           inputFile.clear();
           inputFile.seekg(0);
           int test = 0;

           while(inputFile.tellg()!=end){       
               inputFile.read((char*)&storage[test], sizeof(2));
               cout << "Currently at position" << inputFile.tellg() << endl;
               test++;
           }
           for(int i=0;i<numberOfInts;i++){
               cout << storage[i] << endl;
           }
       }else{
           cout << "Could not open file!!!" << endl;
      }
 }

编辑:::::::::::::::::::::::::::::::::::::::::::::;

我将 read 语句更改为:

      inputFile.read((char*)&storage[test], sizeof(2));

和要键入的数组 short. 现在它运行良好,除了输出有点奇怪:

      In File:        data02b.bin
      8
      Currently at position4
      Currently at position8
      10000
      10002
      10003
      0

我不确定.bin文件中有什么,但我猜 0 不应该在那里。 哈哈

用法:int16_t in <cstdint> .(保证 16 位(

Short s 和 int s 可以具有各种大小,具体取决于体系结构。

是的

,int 是 4 个字节(在 32 位 x86 平台上(。

您有两个问题:

  1. 正如 Alec Teal 在评论中正确提到的那样,您的存储声明为 int,这意味着 4 个字节。没问题,真的 - 您的数据将适合。
  2. 实际问题:您正在读取文件的行:inputFile.read((char*)&storage[test], sizeof(2));实际上是读取 4 个字节,因为 2 是整数,所以sizeof(2)是 4。你不需要那里sizeof

存储被声明为"int"的"数组",sizeof(int(=4

不过这应该不是问题,您可以在 16 位空间中容纳 32 位值,您可能的意思是short storage[...

此外,为了完全公开,size 根据 sizeof(char( 定义为单调递增序列。

4是迄今为止最常见的,因此假设。(限制.h 将澄清(

存储 16 位整数的一种方法是使用 shortunsigned short 类型。

您使用了等于

4 的 sizeof(2),因为 2 是类型 int,因此读取 16 的方法是使storage类型为 short 并读取:

short storage[numberOfInts];
....    
inputFile.read((char*)&storage[test], sizeof(short));

您可以在此处找到包含所有类型大小的表格。