向后打印二进制数

Printing Binary Number Backward

本文关键字:二进制数 打印      更新时间:2023-10-16

我需要向后打印二进制数,而无需显式转换为二进制或使用数组(即,如果二进制数为 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。
  • 字符数组的大小str4,这意味着只有 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';