[英]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位)
根据体系结构, Short
和int
可以具有各种大小。
是的,int是4个字节(在32位x86平台上)。
您有两个问题:
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位整数的一种方法是使用short
或unsigned 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.