LoginSignup
10
4

More than 5 years have passed since last update.

Pythonで2の補数を10進数に変換する

Last updated at Posted at 2018-07-26

Pythonでbit数に関係なく2の補数を10進数に変換する関数を作成してみました。

環境

Python 3.6

2の補数を10進数に変換

shiracamus様にコメント頂いた方を採用させていただきました


def convert_complement_on_two_into_decimal(bits):
    return -int(bits[0]) << len(bits) | int(bits, 2)

廃止
def convert_complement_on_two_into_decimal(bit_data):
return -(int(bit_data, 2) & int(format(2*(len(bit_data)-1), "b"),2)) | (int(bit_data, 2) & int(format(2*(len(bit_data)-1)-1, "0%db" %len(bit_data)), 2))

検証

2の補数で、それぞれのbit数で表現可能な整数の範囲は、-(2^(n-1))~2^(n-1)-1となります(※nはビット数)。

6bitの場合
>>> convert_complement_on_two_into_decimal("100000")
-32
>>> convert_complement_on_two_into_decimal("100001")
-31
>>> convert_complement_on_two_into_decimal("111111")
-1
>>> convert_complement_on_two_into_decimal("000000")
0
>>> convert_complement_on_two_into_decimal("011110")
30
>>> convert_complement_on_two_into_decimal("011111")
31
5bitの場合
>>> convert_complement_on_two_into_decimal("10000")
-16
>>> convert_complement_on_two_into_decimal("01111")
15

参考

コンピュータにおける「データ表現」の基礎(第2回)
2の補数を理解する (1)

shiracamus様にコメント頂く前は、2の補数から10進数への変換ロジックは以下を参考にさせていただきました。
ありがとうございました。
Pythonで符号付き8bit整数を扱う(2の補数)

10
4
3

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
10
4