末尾にdのついた10進数文字列、末尾にhのついた16進数文字列、末尾にbのついた2進数文字列をbitの並びに変換するテスト
def any2bin(valstr: str, is_signed: bool, bitlen: int):
""" 2進数に変換する """
final_char = valstr[-1]
valstr = valstr[:-1]
ret = ''
if final_char == 'b':
if len(valstr) == bitlen:
ret = valstr
else:
raise Exception # 桁数不一致
elif final_char == 'd':
ret = dec2bin(valstr, is_signed, bitlen)
elif final_char == 'h':
ret = hex2bin(valstr, is_signed, bitlen)
else:
raise Exception
return ret
def dec2bin(valstr: str, is_signed: bool, bitlen: int):
"""十進数を二進数のbitが並んだ文字列に変換する"""
val = int(valstr)
if _range_check(val, is_signed, bitlen):
if is_signed and val < 0:
all_one = int('1' * bitlen, base=2) # 1111...1b (bitlen個の1)
ret = f'{~(all_one ^ val): b}'
else:
ret = f'{val:b}'.zfill(bitlen)
else:
raise Exception # out of range
return ret
def hex2bin(valstr: str, is_signed: bool, bitlen: int):
"""16進数を二進数のbitが並んだ文字列に変換する"""
# unsignedとしてbit変換
val = int(valstr, base=16)
maxval = (2 ** bitlen) - 1
if val > maxval:
raise Exception # out of range
ret = f'{val:b}'.zfill(bitlen)
return ret
def _range_check(decval: int, is_signed: bool, bitlen: int):
"""範囲をチェックする"""
ret = True
if is_signed:
min_val = -1 * (2 ** (bitlen-1))
max_val = (2 ** (bitlen - 1)) - 1
else:
min_val = 0
max_val = (2 ** bitlen) - 1
if decval > max_val:
ret = False
if decval < min_val:
ret = False
return ret