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

此生再无相见时 提交于 2019-12-14 03:16:18

问题


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

回答1:


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

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.

Note: this is assuming you're only ever outputting 8 characters at a time, as your code suggests.




回答2:


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


来源:https://stackoverflow.com/questions/26302820/how-do-i-put-a-space-in-between-every-four-characters-in-this-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!