Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary representation of a number in C

I came across this code for the binary representation of a number. I want to know the need for using !! in the 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;
}
like image 614
Zacky112 Avatar asked Feb 06 '10 08:02

Zacky112


People also ask

What is binary representation of a number?

A binary number is a number expressed in the base-2 numeral system or binary numeral system, a method of mathematical expression which uses only two symbols: typically "0" (zero) and "1" (one).

How do you represent 3 in binary?

Since 0000 0011 represents the number 3, we know that 1111 1101 represents the number -3.


2 Answers

!! will convert any non-zero value to 1, and leave zero value as zero.

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

It is a poor man's bool cast.

like image 100
Max Shawabkeh Avatar answered Oct 28 '22 04:10

Max Shawabkeh


The flag used has only the MSB set and all other bits cleared, so that when you bitwise and it with number you can test the MSB in the number.

There are two outcomes of the bitwise anding:

  • Zero - means the number had 0 in its MSB.
  • Non-Zero - means the number had 1 in its MSB.

Now we need a way to map

Non-zero -> 1
Zero -> 0

so we use the double negation.

The same thing could have been done using:

for(i=0;i<sizeof(int)*8;i++) {

    (n & flag) ? printf("1"):printf("0");
    n = n << 1;
}
like image 20
codaddict Avatar answered Oct 28 '22 05:10

codaddict