use*_*893 1 c++ binary byte file
我试图从二进制文件读取一个字节,我得到不准确的结果.
这是二进制文件的内容:
00000000 00 04 0A 07 00 00 00 00 00 00 74 00 00 00 00 61 69 6E 62 6F 77 00 ..........t....ainbow.
关键是我可以读取多个字节,但我只能读取一个字节.如果试图读取0A等于的第三个字节10,而是给我一个32522或十六进制的值7F0A.我在这里错过了什么?
#include <iostream>
#include <fstream>
#include <cstring>
#include <fstream>
using namespace std;
int main()
{
fstream file("foo.daf", ios::in | ios::out | ios::binary);
file.seekg(2);
int x;
file.read(reinterpret_cast<char *>(&x), 1);
cout<<x<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
x 没有初始化,你只修改它的一个字节,所以你有其他字节的垃圾.
直接使用正确的类型应解决您的问题(并避免演员).
char x;
Run Code Online (Sandbox Code Playgroud)
您正在寻找以下代码:
unsigned char x;
file.read(&x, 1);
cout << static_cast<int>(x) << endl;
Run Code Online (Sandbox Code Playgroud)
它读入一个字符,然后将其转换为整数.