1

I am writing my own Servo Driver Program in Python and I struggle quite a bit with Two's (2's) Complement calculation.

Example: I want to have "-100" as an input and get "FF9C" or just "9C" which would also work for the output.

The following picture might help to clarify:

2's calculation I want in python

Poseidon
  • 93
  • 9
Iver
  • 33
  • 8
  • `hex(-100 & 0xffff) == '0xff9c'` and `hex(-100 & 0xff) == '0x9c'`. This of course works with other negative numbers, too. – Michael Butscher Jun 24 '22 at 12:37
  • `n = -100 ; print(f'hex "{n:x}" ; two complement: "{n&(2**16-1):x}"')` -> `hex "-64" ; two complement: "ff9c"` – mozway Jun 24 '22 at 12:40

1 Answers1

1

Thanks so much for the help. I ended up using this for my code for other people having the same difficulty.

n = -100
x = f'{n&(2**16-1):x}'
print(x) # -> ff9c
Iver
  • 33
  • 8