使用std::bitset生成二进制文件

Use std::bitset to produce binary file

本文关键字:二进制文件 bitset std 使用      更新时间:2023-10-16

我使用std::bitset来给我一个数字的二进制表示。我现在想使用它,并只使用二进制表示输出到std::cout-我不想使用std::bitset的ASCII表示-我只想输出我在内存中的位集。

bitset<32> bits = a;
cout << bits; //produces the ASCII characters for '1' and '0' depending on a

如果您的位集在函数to_ulongto_ullong的限制范围内,则可以使用这些函数并将其直接输出到二进制文件中。

如果您的位集超过了unsigned longunsigned long long可以存储的量,则函数将引发溢出异常。这意味着您需要提取位集的子集,并为每个子集将unsigned longunsigned long long存储到文件中。

不幸的是,std::bitset没有提供直接的子集函数,所以您必须自己编写。