c++ - 是否可以将 bitset<8> 转换为整数字符数组?

标签 c++ bitset bitsets

我有bitset<8> v8它的值类似于“11001101”,是二进制的,我们如何在 C++ 中将它转换为字符数组或整数?

最佳答案

要转换为 char 数组,您可以使用 bitset::to_string() 函数获取字符串表示形式,然后从该字符串中复制单个字符:

#include <iostream>
#include <algorithm>
#include <string>
#include <bitset>
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';
}

关于c++ - 是否可以将 bitset<8> 转换为整数字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5005863/

相关文章:

c++ - 用C++获取网络流量

c++ - 在头文件中映射c++

java - 在没有开销的情况下将 BitSet 写入输出文件?

c++ - 如何编写适用于 32 位和 64 位的 std::bitset 模板

c++ - 无法在 CentOS 7 上使用 glibc-2.17 运行 uWebSockets

c++ - Python 嵌入在 c 中。调用 PyRun_SimpleString 是同步的吗?

c++ - bitset 没有成员 ullong

c++ - C++ 中是否有类似双端队列的位集?

c++ - 初始化后如何从字符串中分配位集值

Java多位/紧凑型小整数数组