c++ - 在C++中使用Bitset将16位显示为四组4位

标签 c++ binary output std-bitset

我正在做一项编程作业,我正在使用 C++ 中的 bitset<> 函数打印 16 位整数的二进制表示。我很难尝试将 16 位打印成四组,每组四位,中间有一个空格。我怎样才能用 bitset 函数做到这一点?

cout << "0b" << bitset<16>(integer) << "\t";

如果整数是 1,则打印出来

0b0000000000000001

我要打印的是

0b0000 0000 0000 0001

最佳答案

您可以实现过滤流,但为什么不保持简单呢?

auto the_number = std::bitset<16>(1);

std::cout << "0b";
int count = 0;
for(int i=the_number.size()-1; i>=0; i--)
{
    std::cout << std::bitset<16>(255)[i];
    if(++count == 4) {std::cout << " "; count = 0;}
}

关于c++ - 在C++中使用Bitset将16位显示为四组4位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46258630/

相关文章:

bash - 如何强制 npm bin -g 只打印路径

c++ - LZ77 - 算法 - 分辨率

c++ - 是否可以将一对 <Key, Value> 转换为一对 <const Key, Value>?

c++ - 合并位,然后判断结果有多少个0

c# - 在 C# 中使用 BinaryReader 解析 MNIST 数据集时我做错了什么?

计算无符号整数中的位数

c - 以十列打印到 txt 文件?

hadoop - 使用Multiple Outputs Mapreduce将数据写入多个文件

c++ - 使用linuxtimerfd在Dev pollreactor中实现超时

c - 如何在 C 中使用按位运算符而不使用乘法运算符来乘以 float