LoginSignup
0
0

More than 1 year has passed since last update.

Pythonの2の補数変換

Posted at

文字列に変換したくなかったので以下

def tc(x, bits):
    if x > bits>>1:
        x = ~(x ^ bits)
    return x

ex. 4ビット

>>> tc(7, 0xF)
7
>>> tc(8, 0xF)
-8
>>> tc(0xF, 0xF)
-1

ex. 16ビット

>>> tc(32768, 0xFFFF)
-32768
>>> tc(32767, 0xFFFF)
32767
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0