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;
}
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).
Since 0000 0011 represents the number 3, we know that 1111 1101 represents the number -3.
!!
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.
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:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With