如何在输出中的每四个字符之间留出一个空格
How do I put a space in between every four characters in this output?
我正在编写一个程序,其中必须显示各种数据类型的二进制表示。我需要二进制输出在每四个数字后面有一个空格。例如:
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;
}
相关文章:
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 查找字符在两个索引之间出现的次数
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 转换字符时Arduino DUE 和 Arduino UNO 之间的区别
- 在C++事务之间存储大量字符数据的有效方法
- ifstream 尝试读取 9 到 13 之间的无符号字符时非常奇怪的行为
- 相同字符之间的最小距离
- 打印C++中字符出现之间/之后的所有子字符串
- 常量字符 [] 和常量字符*之间的区别
- 如何将字符串拆分为一组 3 个字符,它们之间有空格
- 在结构之间复制字符数据
- 如何获取字符*的实际长度?strlen 和 sizeof(target)/sizeof(target*)之间的区别?
- 在字符串之间插入字符
- 字符* 和 std::字符串和常量字符*之间的转换
- 使用STD :: String和字符数组之间的选择
- 为什么常量字符[]和常量字符*之间的比较不同
- 字符* 和无符号字符* 之间不兼容
- C++20 中的严格别名规则是否允许标准 c++ unicode 字符和下划线类型之间"reinterpret
- 重命名两个目录中的文件名,如果它们之间的某些字符匹配 - 矢量下标超出范围