Converting to Binary using bitwise and bitshift

∥☆過路亽.° 提交于 2019-12-06 16:49:19

Change decNum & (highestOne >> i) to (decNum & (highestOne >> i)) != 0.

Many people also like to write !!(decNum & (highestOne >> i)). I concede it's cute, but it's less readable and I would suggest that you don't use this.

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");
}

Use

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

That is certainly one way of doing it with the change suggested by Mark, but I think this way is much more readable:

unsigned int decNum = 7;

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

If you would prefer to save a arr, i would recommend the next function:

lets look at the next function that get a unsigned int decNum and convert it to binary:

/*#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");

decNum & (highestOne >> i) just does the evaluation. If the evaluation is true then you should print 1 else if it is false then print 0.

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

NOTE: OTOH, please avoid using magic numbers like 8

R.M.VIVEK Arni
#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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!