is it possible to convert bitset<8> to an array of characters of integers?

前端 未结 2 955
北海茫月
北海茫月 2021-01-24 08:39

I have bitset<8> v8 and its value is something like \"11001101\", something in binary, how can we convert it to an array of characters or integers in c++?

2条回答
  •  忘掉有多难
    2021-01-24 09:15

    To convert to an array of char, you could use the bitset::to_string() function to obtain the string representation and then copy individual characters from that string:

    #include 
    #include 
    #include 
    #include 
    int main()
    {
            std::bitset<8> v8 = 0xcd;
    
            std::string v8_str = v8.to_string();
            std::cout << "string form: " << v8_str << '\n';
    
            char a[9] = {0}; 
            std::copy(v8_str.begin(), v8_str.end(), a);
            // or even strcpy(a, v8_str.c_str());
            std::cout << "array form: " << a << '\n';
    }
    

提交回复
热议问题