-4 & -5 = -8 // How?
-4 & 5 = 4 // How?
I need an explanation for how the above results can be reached. I have no difficulties in solving with positive integers.
When representing integers using a fixed number of bits, negative numbers are typically represented using two's complement. If using n bit numbers, the two's complement of a number x with 0 ≤ x < 2 n 0 \leq x < 2^n 0≤x<2n is ( − x ) mod 2 n = 2 n − x (-x) \mathbin{\text{mod}} 2^n = 2^n - x (−x)mod2n=2n−x.
The result of bitwise-AND can be negative, e.g. (-1) & (-1) is definitely -1 . However, if either operand is nonnegative, the result must also be nonnegative. This is because in 2's complement representation, a negative number must have its 31st bit set, and a nonnegative number must have its 31st bit cleared.
Bitwise operators are used to performing the manipulation of individual bits of a number. They can be used with any integral type (char, short, int, etc.). They are used when performing update and query operations of the Binary indexed trees. This operator is a binary operator, denoted by '|'.
Just convert the integers to their binary representation (for negative integers, use two's complement) and run the bit-wise AND:
-4 11111..1100 &
-5 11111..1011
-8 11111..1000
-4 11111..1100 &
5 00000..0101
4 00000..0100
Let's see how numbers are representing:
positive four 0100
negative four 1100
positive five 0101
negative five 1011
negative eight 1000
If you try to do and
operation manual, you get a result like this:
1100 (-4) & 1011 (-5) = 1000 (-8)
1100 (-4) & 0101 (5) = 0100 (4)
Here you can read more about this.
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