Binary representation of a number in C

I met this code for binary representation of a number. I want to know what to use! in code.

int main() { int n,i; unsigned flag = 1<<(sizeof(int) * 8 - 1); printf("Input the number\n"); scanf("%d",&n); for(i=0;i<sizeof(int)*8;i++) { printf("%d",!!(n & flag) ); n = n << 1; } return 0; } 
+6
c bitwise-operators
source share
3 answers

The flag used has only the MSB set and all other bits are cleared, so when you are bitwise and with a number, you can check the MSB in the number.

There are two results of bitwise handling:

  • Zero - means the number is 0 MSB.
  • Non-Zero - means that the number was 1 in his MSB.

Now we need a way to display

 Non-zero -> 1 Zero -> 0 

therefore we use double negation.

The same could be done using:

 for(i=0;i<sizeof(int)*8;i++) { (n & flag) ? printf("1"):printf("0"); n = n << 1; } 
+7
source share

!! converts any nonzero value to 1 and leave the zero value equal to zero.

 x = 0; y = 50; !x; // 1 !y; // 0 !!x; // 0 !!y; // 1 

This is a poor man, abandoned.

+10
source share

I would write !!x less vaguely like x != 0 .

+2
source share

All Articles