[Python] 2's complement conversion

Overview

Mutual conversion of "numerical value" and "hexary string" in Python. Negative values are two's complement representations.

Code lambda

##2's complement conversion 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)

Code function version

##2's complement conversion function version
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

##for test
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)}")

Execution result. The left is before conversion, the middle is when 2's complement is not considered, and the right is when it is considered.

-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

reference

Convert 2's complement to decimal in Python-Qiita

Recommended Posts

[Python] 2's complement conversion
python unix-time <-> datetime conversion
[S3] CRUD with S3 using Python [Python]
S3 operation with python boto3
Image data type conversion [Python]
Complement python with emacs using company-jedi
Python
Python QT app Standalone App conversion memo
MP3 to WAV conversion with Python
Python executable file conversion module comparison 2
Conversion of string <-> date (date, datetime) in Python
Algorithm learned with Python 7th: Year conversion
Python UTC ⇔ JST, character string (UTC) ⇒ JST conversion memo
Comparison of Japanese conversion module in Python3
PUT gzip directly to S3 in Python
Python learning basics ~ What is type conversion? ~
Python> Format specification when printing `%`> "% s% s"% ('Hello','World',)
Connect to s3 with AWS Lambda Python
Python: Preprocessing in machine learning: Data conversion
Access S3 resources via Cognito in Python
Algorithm learned with Python 3rd: Radix conversion
S3 server-side encryption SSE with Python boto3
String → Bool value conversion in Python Consideration