我需要找到一种方法来获取位集变量中的位序列,并将它们分配给 C++ 中的 uint32 变量。
例如,如果我有一个 bitset<32> 变量为“0xffff ffff”,我想有一个 uint32 变量为 ffff ffff。
我曾经将位序列作为字符串表示形式,但我决定使用位集来保存这些位。从字符串中传输它们会更容易吗?
最佳答案
bitset
有一个 to_ulong
这样做的方法:
unsigned long to_ulong() const;
Convert to unsigned long integer
Returns anunsigned 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/