1. 程式人生 > >bitset和字元陣列的轉換

bitset和字元陣列的轉換

#include <iostream>
#include <bitset>
#include <algorithm>
#include <fstream>
using namespace std;

//c為字串的首地址,n為字串長度
void prt(char * c, int n)
{
    bitset<40> bitset4;
    int pos = 0;
    if (n > 5)
        return;
    for (int i = 0; i < n; ++i)
    {
        for (int j = 7; j >= 0; --j)
        {
            if (c[i] & 1 << j)
            {
                bitset4.set(pos, 1);
            }
            ++pos;
        }
    }    
    char a[10] = { 0 };
    for (int i = 0; i < n; i++)
    {
        for (int j = 7; j >= 0; --j)
        {
            a[i] = a[i] | (bitset4[i*8+7-j] << j);
        }
    }//開啟一個輸出檔案,將字串輸出到檔案中
    ofstream opfile("data.txt", ios_base::out | ios_base::binary);
    opfile.write(reinterpret_cast<char*>(&a), n);
    opfile.close();
}

int main()
{
    char s2[] = "10101";
    prt(s2,5);
    system("pause");
    return 0;
}