1

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

void PrintInBinary( unsigned int decNum )
{
    int i = 0;
    unsigned int highestOne = 1 << (sizeof(unsigned int)*8 - 1);

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


int main()
{
    unsigned int a = 128;
    PrintInBinary( a );
    system("PAUSE");
    return 0;
}

以下是输出:

0000000000000000000000001280000000

基本上,它在每个位位置打印 2^bit 而不仅仅是 1(例如,如果我想将 7 转换为二进制,它将是 0000000...00421 而不是 0000000...00111)。这可能是我想念的微不足道的东西,但是有帮助吗?在过去的 20 分钟里,我一直在做这件事,无法弄清楚这么简单的事情。

4

7 回答 7

3

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

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

于 2012-04-25T18:49:23.427 回答
2
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");
}
于 2012-04-25T19:04:19.133 回答
1

采用

printf( "%u", decNum & (highestOne >> i) > 0 ? 1 : 0 );
于 2012-04-25T18:52:02.763 回答
1

这当然是马克建议的改变的一种方式,但我认为这种方式更具可读性:

unsigned int decNum = 7;

for(i = 0; i < sizeof(int)*8; i++ ) 
{
  printf("%u", ((decNum >> i) & 1));
}
printf("\n");
于 2012-04-25T18:58:07.197 回答
1

如果您希望保存 arr,我会推荐下一个功能:

让我们看看下一个获取 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<size; ++i) {
         int shifted = (decNum >> 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");
于 2013-04-18T11:35:02.353 回答
0

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

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

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

于 2012-04-25T18:54:59.310 回答
0
#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();
}
于 2014-09-23T11:14:18.917 回答