1

I'm working on a Python 3 project. My code is more longer but I prepared for you a sample basic idea of my code which works.

arr = []
arr2 = []
number = (["01", "02", "03" ])
arr = number
print(arr) # Output : ["01", "02", "03"]

Question: How to convert this numbers into another array with converting hex to bin? Note: My expected output is for arr2 : ["00000001", "00000010", "00000011"] And when I print(arr2[0]) I want to see 00000001

Asell
  • 303
  • 1
  • 3
  • 15

3 Answers3

4

You can use the string formatter in a list comprehension:

['{:08b}'.format(int(n, 16)) for n in number]

This returns:

['00000001', '00000010', '00000011']
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

Use the bin function. Convert an int to binary. the [2:] "cuts" the b0 (the function returns etc 03 -> b011) if you want to fill the number with 8 zeros use the zfill(8) function

number = (["01", "02", "03" ])
    arr = []
    for i in number:
        i = int(i)
        i = str(bin(i)[2:]).zfill(8)
        print(i)
        arr.append(str(i))


    print(arr)
Anagnostou John
  • 498
  • 5
  • 14
0

as a one of possible ways:

hex_var = "02"
length = 8

a = bin(int(hex_var, 16))[2:]
print(str(a).zfill(length))
Bogdan
  • 558
  • 2
  • 8
  • 22