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

//读取二进制xxx.bin文件并逐个字节解析//2019.11.10
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;

int main(int argc, char** argv)
{ 

    size_t length;
    ifstream inF;

    inF.open("data.bin", std::ifstream::binary);  //以二进制格式打开文件
    inF.seekg(0, ios::end);                       //将输入指针指向文件末尾
    length = inF.tellg();                         //获取当前指针位置
    cout << "the length of the file is " << length << " " << "byte" << endl;

    unsigned char* data = new unsigned char[length](); //读取文件数组
    inF.seekg(0, ios::beg);                            //将输入指针指向文件开头
    inF.get();
    if (!inF.eof()) {
        cout << "target reading..." << endl;
        inF.read(reinterpret_cast<char*>(data), sizeof(char)* length); //读入文件流
        cout << "finished reading" << endl;
    }
    inF.close();  //关闭文件
    
    cout << "parsing every byte..." << endl; //解析每个字节byte的bit
    
    unsigned char* data0 = new unsigned char[length]; //*****************8bit解析******************//
    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];

    for (size_t i = 0; i < length; i++) { //位运算

        data0[i] = ((data[i] >> 0) & 1);  //第一位
        data1[i] = ((data[i] >> 1) & 1);  //第二位
        data2[i] = ((data[i] >> 2) & 1);  //。。。
        data3[i] = ((data[i] >> 3) & 1);  //。。。
        data4[i] = ((data[i] >> 4) & 1);  //
        data5[i] = ((data[i] >> 5) & 1);  //
        data6[i] = ((data[i] >> 6) & 1);  //
        data7[i] = ((data[i] >> 7) & 1);  //

    }
    delete[] data;
delete[] data0;
delete[] data1;
delete[] data2;

delete[] data3;
delete[] data4;

delete[] data5;
delete[] data6;
delete[] data7;
cout << "finished parsing" << endl;
}

 

posted @ 2020-04-11 21:20  卡冈图雅blackhole  阅读(5937)  评论(0编辑  收藏  举报