繁体   English   中英

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

[英]Reading 16-bit integers from binary file c++

我不确定我是否做对了,所以我想检查一下我的代码。 它有效,但我不确定它是否正确。 我需要它来读取二进制文件,并将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<cstdint> (保证16位)

根据体系结构, Shortint可以具有各种大小。

是的,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

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

另外,为了完全公开,根据sizeof(char)将大小定义为单调递增的序列。

4是迄今为止最常见的一种假设。 (Limits.h将阐明)

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

您使用的sizeof(2)等于4,因为2是int类型的,因此读取16的方法是使类型为short storage和读取:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM