如何在输出中的每四个字符之间留出一个空格

How do I put a space in between every four characters in this output?

本文关键字:之间 字符 空格 一个 四个 输出      更新时间:2023-10-16

我正在编写一个程序,其中必须显示各种数据类型的二进制表示。我需要二进制输出在每四个数字后面有一个空格。例如:

0011 1111 1000 1110 1011 1000 0101 0010

下面是我用来显示二进制代码的函数示例。用空格格式化输出的最佳方式是什么?

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;
}

您已经有了一个计数器,所以您可以使用它来确定您使用的字符。例如:

if(count == 3){
    cout << " ";
}

只需在if-else语句之前添加此if即可。这样,一旦输出了4个字符,count将是3,所以您知道必须输出一个空格。

注意:这是假设您一次只输出8个字符,正如您的代码所建议的那样。

void printChar(char testChar) { 
unsigned char mask = pow(2, ((sizeof(char) * 8) - 1));
//Use an index to store the character number in the current set of 4
unsigned int index = 0;
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);
    index++;
    if(index == 4){
        cout << " ";
        index = 0;
    }
}
cout << endl;
}