[英]Reverse order of bits in a given number
The program I am trying to make asks the user for a number, displays that number in binary, and then reverses the order that the bits in the binary number are displayed in. 我尝试制作的程序要求用户输入数字,以二进制形式显示该数字,然后颠倒二进制数字中的位显示的顺序。
For instance, if I enter the number 1, the output is displayed as 00000001, and the reverse of that would be printed as 10000000. I have been able to get the number to convert to binary, but I'm not sure how to get the reverse output. 例如,如果我输入数字1,则输出将显示为00000001,而其输出将显示为10000000。我已经能够将数字转换为二进制,但是我不确定如何获取反向输出。
Any suggestions? 有什么建议么? I have provided my code below so that I can show where I am at in this program.
我在下面提供了我的代码,以便可以显示我在此程序中的位置。
void print_bits(unsigned char x) {
int i = 0;
for (i = 7; i >= 0; i--) {
printf("%d", (x & (1 << i)) >> i);
}
printf("\n");
}
int main(int argc, char * argv[]) {
unsigned char x;
printf("Enter a number: ");
scanf("%hhu", &x);
printf("Bits: ");
print_bits(x);
return 0;
}
Just do the opposit for loop when printing: 只需在打印时执行相反的循环:
for (i = 0; i <= 7; i++) {
printf("%d", (x & (1 << i)) >> i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.