LoginSignup
1
0

任意の数値をBCDに変換する / Python / double dabbleアルゴリズムと少しインチキな方法と

Last updated at Posted at 2021-04-26
"""
# 普通に10進数の1桁ずつを取り出す。
def bin2bcd(_bin):
    DIGITS_BCD = len(str(_bin))
    bcd = [0] * DIGITS_BCD
    for i in range(DIGITS_BCD - 1):
        _bin, bcd[i] = divmod(_bin, 10)
    bcd[DIGITS_BCD - 1] = _bin
    return bcd
"""

# double dabbleアルゴリズム
def to_bcd_dubdab(_bin):
    DIGITS_BCD = len(str(_bin)) # BCD表現での桁数
    BITS_BCD   = DIGITS_BCD * 4 # その2進数表現での桁数
    
    bcd = 0
    for i in range(BITS_BCD - 1, 0, -1):
        bcd = bcd << 1 | (_bin >> i & 1)
        for j in range(BITS_BCD, -1, -4):
            if (bcd >> j & 0xF) > 4:
                bcd += 3 << j
    return bcd << 1 | (_bin & 1)
        
# 少しインチキな方法
def to_bcd(val):
    # 元の数値を10進数文字列に変換して、
    # それを16進数文字列であると見なして、
    # 数値に戻して返す。
    return eval("0x" + str(val))

# この値をBCDに変換してみる。
val = 9876543210

"""
# 普通に10進数の1桁ずつを取り出した結果
print(bin2bcd(val))
"""

# double dabbleアルゴリズムによる結果(を16進数文字列にして確かめる)
print(hex(to_bcd_dubdab(val)))

# 少しインチキな方法による結果(を16進数文字列にして確かめる)
print(hex(to_bcd(val)))

実行結果:
image.png

1
0
3

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
1
0