# [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))

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