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

2
  • hex(-100 & 0xffff) == '0xff9c' and hex(-100 & 0xff) == '0x9c'. This of course works with other negative numbers, too. Commented Jun 24, 2022 at 12:37
  • n = -100 ; print(f'hex "{n:x}" ; two complement: "{n&(2**16-1):x}"') -> hex "-64" ; two complement: "ff9c" Commented Jun 24, 2022 at 12:40

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.