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

时间:2012-04-25 18:48:31

标签: c bit-manipulation bit-shift

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

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 ^位而不是只打1(例如,如果我想将7转换为二进制,则它将是0000000 ... 00421而不是0000000 ... 00111)。这可能是我所遗漏的微不足道的事情,但任何有帮助的人呢?我在过去的20分钟里一直在这里,因此无法弄清楚这么简单。

7 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分: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");
}

答案 2 :(得分:1)

使用

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

答案 3 :(得分:1)

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

unsigned int decNum = 7;

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

答案 4 :(得分: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");

答案 5 :(得分:0)

decNum & (highestOne >> i)只进行评估。如果评估为true,则应打印1否则为false,然后打印0

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

注意:OTOH,请避免使用像8

这样的幻数

答案 6 :(得分: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();
}