使用按位和bitshift转换为二进制

我正在尝试使用按位和位移创建一个以二进制打印数字的函数,但是我无法正确打印它。 以下是我的代码。

void PrintInBinary( unsigned int decNum ) { int i = 0; unsigned int highestOne = 1 << (sizeof(unsigned int)*8 - 1); for( i = 0; i > i) ); } printf("\n"); } int main() { unsigned int a = 128; PrintInBinary( a ); system("PAUSE"); return 0; } 

以下是输出:

 0000000000000000000000001280000000 

基本上,它打印2 ^位而不是每个位位置只有1(例如,如果我想将7转换为二进制,则它将是0000000 … 00421而不是0000000 … 00111)。 这可能是我所遗漏的微不足道的事情,但任何有帮助的人呢? 在过去的20分钟里,我一直在这里,无法弄清楚这么简单的事情。

decNum & (highestOne >> i)更改为(decNum & (highestOne >> i)) != 0

很多人也喜欢写!!(decNum & (highestOne >> i)) 。 我承认它很可爱,但它的可读性较差,我建议你不要使用它。

 void PrintInBinary( unsigned int decNum ) { unsigned int bit; for( bit = 1u << (CHAR_BIT*sizeof bit -1); bit; bit >>= 1 ) { printf( "%c", decNum & bit ? '1' : '0' ); } printf("\n"); } 

使用

 printf( "%u", decNum & (highestOne >> i) > 0 ? 1 : 0 ); 

这肯定是用Mark建议的改变的一种方式,但我认为这种方式更具可读性:

 unsigned int decNum = 7; for(i = 0; i < sizeof(int)*8; i++ ) { printf("%u", ((decNum >> i) & 1)); } printf("\n"); 

如果你想保存一个arr,我会推荐下一个function:

让我们看看下一个获得unsigned int decNum并将其转换为二进制的函数:

 /*#define BITS 8*/ int size = sizeof(unsigned int)*BITS; char arr[size] ; int i; /* now lets thinkk... shift by i=0 to the right: 4 = 00...00 0100 & 1 = 00...00 0001 ----------------- 00...00 0000 now we know that we need to enter 0 in the 1-rd place in the arr shift by i=1 to the right: 4 = 00...00 0010 & 1 = 00...00 0001 ----------------- 00...00 0000 now we know that we need to enter 0 in the 2-rd place in the arr shift by i=2 to the right: 4 = 00...00 0001 & 1 = 00...00 0001 ----------------- 00...00 0001 now we know that we need to enter 1 in the 3-rd place in the arr and so on... */ for(i=0; i> i); arr[(size-1)-i] = (shifted&1)?'1':'0'; } printf("The binary of %d in %d bits:\n",decNum, size); /*now lets print the array*/ for (i=0; i < size ; i++){ printf("%c",arr[i]); } printf("\n"); 

decNum & (highestOne >> i)只进行评估。 如果评估为true那么你应该打印1 ,如果它是false则打印0

 decNum & (highestOne >> i) ? 1 : 0 

注意:OTOH,请避免使用像8这样的幻数

 #include"stdio.h" #include"conio.h"//this coding f void main() { int rm,vivek; clrscr(); printf("enter the values"); scanf("%d",&rm); printf("enter the no.of times moves"); scanf("%d",&vivek); printf("the value rm=%d>>vivek=%doutput=%u",rm,vivek,rm>>vivek);//5>>1 getch(); }