向后打印二进制数
Printing Binary Number Backward
我需要向后打印二进制数,而无需显式转换为二进制或使用数组(即,如果二进制数为 10,则应打印为 01(。这是我为向前打印数字所做的代码。我相当确定我只需要告诉代码从另一端开始运行循环,以便让数字向后呈现。但是,我不知道该怎么做,或者这是否正确。
奖励问题 - 有人可以引导我完成这段代码的真正作用吗?它是从我们在课堂上得到的修改而来的,我不完全理解它的实际作用。
注意:我一直使用的测试用例是 50。
#include <stdio.h>
char str [sizeof(int)];
const int maxbit = 5;
char* IntToBinary (int n, char * BackwardBinaryString) {
int i;
for(i = 0; i <= maxbit; i++) {
if(n & 1 << i) {
BackwardBinaryString[maxbit - i] = '1';
}
else {
BackwardBinaryString[maxbit - i] = '0';
}
}
BackwardBinaryString[maxbit + 1] = ' ';
return BackwardBinaryString;
}
int main () {
int base10input;
scanf("%d", &base10input);
printf("The backwards binary representation is: %sn", IntToBinary(base10input, str));
return 0;
}
令你失望的是,你的代码在这些方面是错误的。
sizeof(int)
返回 int 占用的字节数,但我们需要将每个位存储在 char 中时所需的位,因此我们需要将其乘以 8。- 字符数组的大小
str
4,这意味着只有 str[0] 到 str[3] 有效。但是,您修改了超出界限的 str[4]、str[5] 和 str[6],这种未定义的行为将导致灾难。
您首先应该做的是创建一个包含至少sizeof(int) * 8 + 1
个字符的数组(sizeof(int) * 8
用于二进制表示,一个用于空终止符( 然后开始你的约定。
我还建议 str 不应该是一个全局变量。最好是主函数的局部变量。
您的代码应该像这样修改。我已经在评论中解释了它的作用。
#include <stdio.h>
#define INTBITS (sizeof(int) * 8) // bits an integer takes
char* IntToBinary(int n, char* backwardBinaryString) {
// convert in reverse order (str[INTBITS - 1] to str[0])
// remember that array subscript starts from 0
for (int i = 0; i < INTBITS; i++) {
// (n & (1 << i)) checks the i th bit of n is 0 or 1
// if it is 1, the value of this expression will be true
if (n & (1 << i)) {
backwardBinaryString[INTBITS - 1 - i] = '1';
}
else {
backwardBinaryString[INTBITS - 1 - i] = '0';
}
// here replacing the if-else with and conditional operator like this
// will make the code shorter and easier to read
// backwardBinaryString[INTBITS - 1 - i] = (n & (1 << i)) ? '1' : '0';
}
// add the null-terminator at the end of str (str[INTBITS + 1 - 1])
backwardBinaryString[INTBITS] = ' ';
return backwardBinaryString;
}
int main() {
char str[INTBITS + 1];
int base10input;
scanf("%d", &base10input);
printf("The backwards binary representation is: %sn", IntToBinary(base10input, str));
return 0;
}
该代码比它需要的要复杂得多。由于要求是打印位,因此无需存储它们。只需在生成每个时打印即可。反过来,这意味着您无需使用i
来跟踪正在生成的位:
if (n == 0)
std::cout << '0';
else
while (n != 0) {
std::cout << (n & 1) ? '1' : '0';
n >>= 1;
}
std::cout << 'n';
相关文章:
- visual在c++中将十进制数转换为二进制数
- 二进制数之和(使用C样式字符串)
- 以 10 c++ 为基数显示 1024 位二进制数
- 二进制数和位标志'x'
- 错误含义;以二进制形式打印数字
- C++ 二进制数到整数值的数组
- 二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位
- dev如何在C++中比较二进制数
- 递归回溯打印长度为N的二进制数的所有组合,而不使用循环
- 如何通过输入十进制数打印UTF-8符号?
- 向后打印二进制数
- 使用位黑客反转二进制数
- 添加两个二进制数(整数数组)
- 从 0 到 n 的二进制数,具有相同数量的字符/
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- 所有测试用例都将小数点转换为二进制数
- 尝试将二进制数组转换为十六进制C++然后打印结果
- 如何缩放二进制数组以保留值
- 计数二进制数中连续1的数量
- 二进制数的前导零不会被打印