Skip to content

Instantly share code, notes, and snippets.

@msymt
Last active August 16, 2022 06:40
Show Gist options
  • Save msymt/479db290755c6789c3d4043bd2878a79 to your computer and use it in GitHub Desktop.
Save msymt/479db290755c6789c3d4043bd2878a79 to your computer and use it in GitHub Desktop.
12ビットの符号付き整数の16進数を10進数に変換するプログラム
"""
12ビットの符号付き整数の16進数(1桁+2桁が別の変数) -> 10
data1: 4bit
data2: 12bit
total: 16bit
"""
# data1: 0xF, data2: 0xFF
def convert_two_complement_hex_to_dec(data1, data2):
bits = 12
# 0xF, 0xFF -> FFF
# format(data2, '02x'): 2桁の16進数に変換し、1桁の場合は0埋めする
data = format(data1, 'x') + format(data2, '02x')
# hex to dec
value = int(data, 16)
# most significant bitが1のとき、2の補数を返す
if value & (1 << (bits - 1)):
value = value - (1 << bits)
return value
def testcase(data1, data2, ans):
res = convert_two_complement_hex_to_dec(data1, data2)
assert res == ans
testcase(data1 = 0xF, data2 = 0xFF, ans = -1)
testcase(data1 = 0x7, data2 = 0xFF, ans = 2047)
testcase(data1 = 0x8, data2 = 0x00, ans = -2048)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment