Asell
Asell

Reputation: 303

Coverting hex to bin and putting in another array Python 3

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

Upvotes: 1

Views: 69

Answers (3)

Anagnostou John
Anagnostou John

Reputation: 514

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)

Upvotes: 1

Bogdan
Bogdan

Reputation: 608

as a one of possible ways:

hex_var = "02"
length = 8

a = bin(int(hex_var, 16))[2:]
print(str(a).zfill(length))

Upvotes: 0

blhsing
blhsing

Reputation: 106533

You can use the string formatter in a list comprehension:

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

This returns:

['00000001', '00000010', '00000011']

Upvotes: 4

Related Questions