-1

Several previously asked questions such as this and this mention only why this happens i.e. 2's compliment. I need help with how to convert this :

print("if ~(0b11011111) is "+str(bin(~(0b1101111))) +" not 0b00100000")
print("and ~(0b00100000) is  " +str(bin(~(0b00100000)))+" not 11011111")

Output :

if ~(0b11011111) is -0b1110000 not 0b00100000
and ~(0b00100000) is  -0b100001 not 11011111

Can anyone help me with how to do this?

  • What have you tried so far? – Daweo Oct 12 '22 at 10:47
  • @Daweo I worked on bitwise operator for Arduino project based on Arduino C. using same ~ operator. It was long ago but I remember it was the same way. Now I was writing code in Python it just not working showing negative values. I look for unsigned int in python I couldn't understand much about it. Its seems like in examples they are squaring the number to achieve in. – Just doin Gods work Oct 12 '22 at 10:50
  • I believe there a way to do it with unsigned definition but not 100% sure – Just doin Gods work Oct 12 '22 at 10:51
  • I refer you to https://stackoverflow.com/questions/1604464/twos-complement-in-python – DarkKnight Oct 12 '22 at 10:56
  • if I only have 8 bits, is there any better way than this `0x100+~(0b00100000)` – Just doin Gods work Oct 12 '22 at 11:05

1 Answers1

1

When you have a fixed number of bits, inverting them is easy — just invert them. So, for example, it we are working with 4-bit integers, the inverse of 5 (0b0101) is 0b1010

However, Python has arbitrary-sized integers, which makes things a bit tricker. If we invert 5 (0b101), is the result 1010 or 11111010 or 1111111111111010 or what? So Python defines inverting in terms of integers (in the mathematical sense, as opposed to strings of bits); ~x ≝ -(x+1). Why this definition? When working with two’s-complement representation of negatives, neg(x) = inv(x)+1 so it makes sense that inv(x) = neg(x)-1 = -(x+1). This is why ~5 comes out to -6.

So that is why you are getting negative numbers, but how do you get the positive value that you expect? The language spec does not say it explicitly, but the bitwise & and | operators seem to treat negatives as having “enough” ones on the left. This means that if you mask out only as many bits to the right as you want, you get a positive number. For example, if we want to invert a 4-bit number 5, we can do bin(~0b101 & 0b1111 and get the expected 0b1010.

You seem to be expecting 8-bit numbers, so for example bin(~0b00100000 & 0xff) gives you 0b11011111.

Ture Pålsson
  • 6,088
  • 2
  • 12
  • 15