bitset和字符数组的转换

#include
#include
#include
#include
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(&a), n);
    opfile.close();
}

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

你可能感兴趣的:(C++基础)