Search code examples
cbinaryoctal

Diffrent usage of &- operator


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?


Solution

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