gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:37 25 4
gpt4 key购买 nike

我正在做一项编程作业,我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com