问题
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