C语言移位问题

来源:百度知道 编辑:UC知道 时间:2024/06/15 17:19:27
#include<stdio.h>
void printb(int,int);
int main()
{
int x;
printf("%d",sizeof(int));
printf("Input number:");
scanf("%d",&x);
printf("number of decimal form:%d\n",x);
printf(" it's binary form:");

printb(x,sizeof(int)*8); /*x:整数 sizeof(int):int型在内存中所占的字节数
sizeof(int)*8:int型对应的位数*/
putchar('\n');
getch();
}
void printb(int x,int n)
{
if(n>0)
{
putchar('0'+((unsigned)(x&(1<<(n-1)))>>(n-1))); /*输出第n位*/
printb(x,n-1); /*归调用,输出x的后n-1位*/
}
}
这道题的题目是将任一整数转换为二进制形式
putchar('0'+((unsigned)(x&(1<<(n-1)))>>(n-1))); /*输出第n位*/这条语句到底是怎么运行的 举例说明

我举个例子哈,但愿看得懂。

x = 255 = 00000000000000000000000011111111
n = 8
y = 1 << (8 - 1) = 00000000000000000000000010000000
z = x & y = 00000000000000000000000010000000
z >> (8 - 1) = 00000000000000000000000000000001
putchar(z) 输出的就是第8位上的数字1

实际上那个putchar可以改成:
putchar('0'+((x >> (n-1)) & 0x1));