[英]Using Bitset to display 16 bits into four groups of 4 bits in C++
I'm working on a programming assignment and I am using the bitset<> function in C++ to print put the binary representation of an integer by 16 bits. 我正在进行编程任务,正在C ++中使用bitset <>函数打印16位整数的二进制表示形式。 I am having a hard time trying to print the 16 bits into four groups of four bits with a space in between.
我很难将16位打印成四组,每组四位,中间有一个空格。 How can I do that with a bitset function?
如何使用位集功能做到这一点?
cout << "0b" << bitset<16>(integer) << "\t";
This prints out if the integer was 1 如果整数为1,则打印输出
0b0000000000000001
What i am trying to print out is 我要打印的是
0b0000 0000 0000 0001
You could implement a filtering stream, but why not keep it simple? 您可以实现过滤流,但是为什么不保持它简单呢?
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;}
}
The <<
-operator for bitsets does not provide a format specifier that separates the nibbles. <<
的运算符不提供分隔半字节的格式说明符。 You'll have to iterate through the bits on your own and introduce separators "manually": 您必须自己遍历各个位并“手动”引入分隔符:
int main() {
int integer = 24234;
bitset<16> bits(integer);
cout << "0b";
for (std::size_t i = 0; i < bits.size(); ++i) {
if (i && i%4 == 0) { // write a space before starting a new nibble (except before the very first nibble)
cout << ' ';
}
std::cout << bits[bits.size() - i - 1];
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.