c++ - 如何将bitset变量的内容存储到c中的uint32

标签 c++

我需要找到一种方法来获取位集变量中的位序列,并将它们分配给 C++ 中的 uint32 变量。

例如,如果我有一个 bitset<32> 变量为“0xffff ffff”,我想有一个 uint32 变量为 ffff ffff。

我曾经将位序列作为字符串表示形式,但我决定使用位集来保存这些位。从字符串中传输它们会更容易吗?

最佳答案

bitset 有一个 to_ulong这样做的方法:

unsigned long to_ulong() const;
Convert to unsigned long integer
Returns an unsigned long with the integer value that has the same bits set as the bitset.

例子:

#include <bitset>
#include <iostream>

int main(void)
{
    std::bitset<32> b(0xffffffff);
    uint32_t i = b.to_ulong();

    std::cout << b << std::endl;
    std::cout << std::hex << i << std::endl;

    return 0;
}

构建并运行:

$ make example && ./example
c++     example.cpp   -o example
11111111111111111111111111111111
ffffffff

关于c++ - 如何将bitset变量的内容存储到c中的uint32,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18970336/

相关文章:

C++ constexpr 与字符串文字中的宏与整数

c++ - 在 CUDA 内核中使用 Eigen 3.3

c++ - 将 0A 替换为\n

c++ - 为什么我们需要使用 virtual ~A() = default;而不是 C++11 中的虚拟 ~A() {}?

C++ 容器行为

c++ - 我想念什么吗?

c++ - 这是对具有 C++ 继承层次结构的 namespace 的合理使用吗?

c++ - 使用 string::find 解析文件

c++ - 如何纠正水平翻转功能以防止其改变图像的颜色

c++ - C++ 中引用使用的影响