Question

my hex string is 0e0010000001020c93b2

its equivalent BCD string(online generator) is 01100110000100010100001010000011011010000001011010000011100101101001000110000100011010010000

How can I do it python?

Was it helpful?

Solution

Like this, for example:

>>> ''.join(format(int(c), '04b') for c in str(int('0e0010000001020c93b2', 16)))
    '0110011000010001010000101000001101101000000101\
     1010000011100101101001000110000100011010010000'

Explained:

>>> hex_string = '0e0010000001020c93b2'

>>> decimal_int = int(hex_string, 16)
>>> decimal_int
66114283681683969184690L

>>> decimal_string = str(decimal_int)
>>> decimal_string
'66114283681683969184690'

>>> digits = [int(c) for c in decimal_string]
>>> digits
[6, 6, 1, 1, 4, 2, 8, 3, 6, 8, 1, 6, 8, 3, 9, 6, 9, 1, 8, 4, 6, 9, 0]

>>> zero_padded_BCD_digits = [format(d, '04b') for d in digits]
>>> zero_padded_BCD_digits
['0110', '0110', '0001', '0001', '0100', '0010', '1000', '0011', '0110', '1000',
'0001', '0110', '1000', '0011', '1001', '0110', '1001', '0001', '1000', '0100',
'0110', '1001', '0000']

>>> ''.join(zero_padded_BCD_digits)
'0110011000010001010000101000001101101000000101\
 1010000011100101101001000110000100011010010000'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top