views:

171

answers:

3

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;
}
+7  A: 

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;
}
codaddict
MSB = Most Significant Bit
pug
alternately, `printf(((n `
Hasturkun
+10  A: 

!! 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.

Max Shawabkeh
In some implementations of C, it'll be 0 or -1 rather than 0 or 1.
T.J. Crowder
Not if the implementation is standards compliant. According to the current draft standard 6.3.1.2, "When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1."
Chinmay Kanchi
@T.J. Crowder: No. Logical operators are guaranteed to evaluate to 0 or 1. Specifically: "The result of logical negation is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0." (6.5.3.3/5 of the C99 standard)
jamesdlin
+2  A: 

I would write !!x less confusingly as x != 0.

starblue