Reputation:
Look at the following code:
#include <stdio.h>
int main()
{
int num, sum;
scanf("%d", &num);
sum = num - (num&-num);
printf("%d", sum);
return 0;
}
The line sum = num - (num& - num)
returns value of the given number without the last 1 in binary format. For example if the num is equal to 6(110) it will give the value without the last 1. In this case 100 which is equal to 4.
My question is how does &-
work and how could do we do the same thing in octal numeral system?
Upvotes: 2
Views: 89
Reputation: 222302
There is no &-
operator. num - (num&-num)
is num - (num & -num)
, where &
performs the bitwise AND of num
and its negation, -num
.
Consider some number in binary, say 0011 0011 1100 11002 (spaces used for easy visualization). The negative of this is −0011 0011 1100 11002. However, we commonly represent negative numbers using two’s complement, in which a power of two is added. For 16-bit formats, we add 216, which is 1 0000 0000 0000 00002. So, to represent −0011 0011 1100 11002, we use 1 0000 0000 0000 00002 + −0011 0011 1100 11002 = 1100 1100 0011 01002.
Observe what happens in this subtraction, column by column from the right:
Thus the result is:
Thus the subtrahend (the number being subtracted) and the result differ in all bits to the left of the first 1. And they both have 0s to the right of the first 1. So the only bit they both have set is that first 1.
Therefore, when two’s complement is in use, the result of num & -num
is the lowest 1 bit that is set in num
.
Then num - (num & -num)
subtracts this bit from num
, leaving it as num
with its lowest 1 bit changed to 0.
Upvotes: 3
Reputation: 223689
What you have here is two separate operators: the bitwise AND operator &
and the unary negation operator -
. So the line in question is actually:
sum = num - (num & -num);
Assuming integers are stored in two's complement representation, negating a value means inverting all bits and adding one.
In the case that num
is 6, (binary 00000110), -num
is -6 which is 11111010. Then performing a bitwise AND between these two values results in 00000010 in binary which is 2 in decimal, so num - (num & -num)
is 6 - 2 which is 4.
Upvotes: 3