如何在此输出中的每四个字符之间放置一个空格? [英] How do I put a space in between every four characters in this output?
问题描述
我正在编写一个程序,其中必须显示各种数据类型的二进制表示形式.我需要二进制输出每四个数字后有一个空格.例如:
I am writing a program where I have to display binary representations of various data types. I need the binary output to have a space after every four numbers. For instance:
0011 1111 1000 1110 1011 1000 0101 0010
下面是我用来显示二进制代码的函数示例.用空格格式化输出的最佳方法是什么?
Below is sample of a function I am using to display the binary code. What is the best way to format the output with the spaces?
void printChar(char testChar)
{
unsigned char mask = pow(2, ((sizeof(char) * 8) - 1));
cout << "The binary representation of " << testChar << " is ";
for (int count = 7; count >= 0; count--)
{
if ((testChar & mask) != 0)
{
cout << "1";
}
else
{
cout << "0";
}
mask = (mask >> 1);
}
cout << endl;
}
推荐答案
您已经有了一个计数器,因此您可以使用它来确定正在使用哪个字符.例如:
You already have a counter going, so you can just use that to determine which character you're on. For example:
if(count == 3){
cout << " ";
}
只需在if-else
语句之前添加此if
.这样,一旦您输出了4个字符,count
将为3,因此您知道必须输出一个空格.
Just add this if
before your if-else
statement. That way, once you have outputted 4 characters, count
will be 3, so you know you have to output a space.
注意:这是假设您一次只能输出8个字符,如代码所示.
Note: this is assuming you're only ever outputting 8 characters at a time, as your code suggests.
这篇关于如何在此输出中的每四个字符之间放置一个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!