2019-11-07

c/c++读取二进制.bin文件并逐个字节解析为bit

#include

#include

using namespace std;

int main(int argc, char** argv)

{

unsigned int length;

ifstream inF;

inF.open("文档名称.bin", std::ifstream::binary);  //以二进制格式打开文件

inF.seekg(0, ios::end);  //将输入指针指向文件末尾

length = inF.tellg();    //获取当前指针位置

//创建数组0~7

unsigned char* data = new unsigned char[length]();

unsigned char* data0 = new unsigned char[length];

unsigned char* data1 = new unsigned char[length];

unsigned char* data2 = new unsigned char[length];

unsigned char* data3 = new unsigned char[length];

unsigned char* data4 = new unsigned char[length];

unsigned char* data5 = new unsigned char[length];

unsigned char* data6 = new unsigned char[length];

unsigned char* data7 = new unsigned char[length];

inF.seekg(0, ios::beg);  //将输入指针指向文件开头

inF.get();

while (!inF.eof()) {

  inF.read(reinterpret_cast(data), sizeof(char) * length);  //开始读取

}

inF.close();  //关闭文件

//解析每个字节byte的bit

for (unsigned int i = 0; i < length; i++) {

data0[i] = ((data[i] >> 0) & 1);  //0

data1[i] = ((data[i] >> 1) & 1);  //1

data2[i] = ((data[i] >> 2) & 1);  //2

data3[i] = ((data[i] >> 3) & 1);  //3

data4[i] = ((data[i] >> 4) & 1);  //4

data5[i] = ((data[i] >> 5) & 1);  //5

data6[i] = ((data[i] >> 6) & 1);  //6

data7[i] = ((data[i] >> 7) & 1);  //7

}

//输出

for (unsigned int j = 0; j < length; j++) {

cout << (unsigned short int)data7[j] << endl;

cout << (unsigned short int)data6[j] << endl;

cout << (unsigned short int)data5[j] << endl;

cout << (unsigned short int)data4[j] << endl;

cout << (unsigned short int)data3[j] << endl;

cout << (unsigned short int)data2[j] << endl;

cout << (unsigned short int)data1[j] << endl;

cout << (unsigned short int)data0[j] << endl;

}

delete[] data0;

delete[] data1;

delete[] data2;

delete[] data3;

delete[] data4;

delete[] data5;

delete[] data6;

delete[] data7;

delete[] data;

return 0;

}

连接https://www.jianshu.com/writer#/notebooks/40673762/notes/56069465

你可能感兴趣的:(2019-11-07)