0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python】2の補数変換

Posted at

概要

Pythonで「数値」と「16進数文字列」の相互変換。
マイナス値は、2の補数表現。

コード lambda

## 2の補数変換 lambda
bits = 8

all_one = (1<<bits) - 1
int2ss = lambda i: hex(i & all_one)
## int2ss = lambda i: hex(i & ((1<<bits) - 1))

sign_mask = (1<<(bits-1))
ss2int = lambda s: -(int(s,16) & sign_mask) | int(s,16)
## ss2int = lambda s: -(int(s,16) & (1<<(bits-1))) | int(s,16)

コード 関数版

## 2の補数変換 関数版
def int_to_signed_string(i, bits):
    return hex(i & ((1<<bits) - 1))

def signed_string_to_int(s, bits):
    ss = int(s,16)
    return -(ss & (1<<(bits-1))) | ss

## テスト用
bits = 8
int2ss = lambda i: int_to_signed_string(i, bits)
ss2int = lambda s: signed_string_to_int(s, bits)

Test

test = [-128, -127, -2, -1, 0, 1, 2, 126, 127]
test_str_hex = []

for t in test:
    print(f"{t}: {hex(t)}, {int2ss(t)}")
    test_str_hex.append(int2ss(t))

print("---")

for t in test_str_hex:
    print(f"{t}: {int(t, 16)}, {ss2int(t)}")

実行結果。
左が変換前、真ん中が2の補数を考慮しない場合、右が考慮した場合。

-128: -0x80, 0x80
-127: -0x7f, 0x81
-2: -0x2, 0xfe
-1: -0x1, 0xff
0: 0x0, 0x0
1: 0x1, 0x1
2: 0x2, 0x2
126: 0x7e, 0x7e
127: 0x7f, 0x7f
---
0x80: 128, -128
0x81: 129, -127
0xfe: 254, -2
0xff: 255, -1
0x0: 0, 0
0x1: 1, 1
0x2: 2, 2
0x7e: 126, 126
0x7f: 127, 127

参考

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

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?