0
我试图用C++读取一个字节文件(目标:二进制数据格式反序列化)。 DAT文件看起来像下面的Hex Editor(bytes.dat):cpp字节文件读取
但读二进制文件转换成字符数组出问题的时候..这里是一个兆瓦:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ofstream outfile;
outfile.open("bytes.dat", std::ios::binary);
outfile << hex << (char) 0x77 << (char) 0x77 << (char) 0x77 << (char) 0x07 \
<< (char) 0x9C << (char) 0x04 << (char) 0x00 << (char) 0x00 << (char) 0x41 \
<< (char) 0x49 << (char) 0x44 << (char) 0x30 << (char) 0x00 << (char) 0x00 \
<< (char) 0x04 << (char) 0x9C;
ifstream infile;
infile.open("bytes.dat", ios::in | ios::binary);
char bytes[16];
for (int i = 0; i < 16; ++i)
{
infile.read(&bytes[i], 1);
printf("%02X ", bytes[i]);
}
}
但是这显示了COUT(MinGW的编译):
> g++ bytes.cpp -o bytes.exe
> bytes.exe
6A 58 2E 76 FFFFFF9E 6A 2E 76 FFFFFFB0 1E 40 00 6C FFFFFFFF 28 00
即时做错了什么。在某些数组条目中有4个字节可能如何?
申报'bytes'如一个'unsigned char'数组或''将字节'我''转换为'unsigned char'。 – 2014-09-02 13:54:38
tnx解决了长时间的FFFFFF问题。但是这些值不是十六进制编辑器中的内容 – Walter 2014-09-02 13:55:52
使用['outfile.write()'](http://en.cppreference.com/w/cpp/io/basic_ostream/write)而不是'operator << '存储二进制数据。 – 2014-09-02 13:56:25