Bitwise: Why 14 & -14 is equals to 2 and 16 & -16 is equals to 16?

Question:

it is a dummy question, but I need to understand it more deeply

Asked By: Rudda Beltrao

||

Answers:

A bitwise operation is a binary operation.

In some representations of integers, one bit is used to represent the sign of the number. Depending upon which bit that is, will change the result of the bitwise &. In 2’s complement, negative numbers are represented by inverting all the bits and then adding 1. There are many ways of representing real numbers in binary. Regardless, generally, a bitwise operation of a positive and negative number will always result in undefined behaviour. Probably why most calculators will only allow positive integers in bitwise operations. That is, calculators that are advanced enough to have such a feature.

EDIT: The specific numbers you chose are significant. The number 14 is represented in binary using less bits than 16. It just so happens that -16 and 16 are both exactly the same binary (looking only at the first five bits, since the rest are not significant when you come to & them together)

Now a bitwise & only sets a bit if that bit is set in both the numbers you are and-ing together.

1110 = 14

0010 = -14

&0010 = 2!

10000 = 16

10000 = -16

&10000 = 16!

There’s your answer.

Answered By: Noscere

Python integers use two’s complement to store signed values. That means that positive numbers are stored simply as their bit sequence (so 14 is 00001110 since it’s equal to 8 + 4 + 2). On the other hand, negative numbers are stored by taking their positive quantity, inverting it, and adding one. So -14 is 11110010. We took the bitwise representation of 14 (00001110), inverted it (11110001), and added one (11110010).

But there’s an added wrinkle. Python integer values are bignums; they can be arbitrarily large. So our usual notion of "this number is stored in N bits" breaks down. Instead, we may end up with two numbers of differing lengths. If we end up in that situation, we may have to sign extend the shorter one. This is just a fancy way of saying "take the most significant bit and repeat it until the number is long enough for our liking".

So in the case of 14 and -14, we have

0010
1110

We & them together. Only the second bit (counting from the right, or least significant bit) is true in both, so we get 0010, or 2. On the other hand, with 16 and -16, we get

010000
110000

For -16, we took positive sixteen (010000), flipped all of the bits (101111), and then added one, which got carried all the way over to the second most significant bit (110000). When we & these, we get 16.

010000

See also BitwiseOperators – Python Wiki

Answered By: Silvio Mayolo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.