Search code examples
pythonstringbinarybitconverters

how to make binary to bit 8 in python


i have variable contains with binary with type int ([101, 1101, 11001]) but i want to xor it with another variable, so i must change to string and add "0" so it has 8 number example 101 it'll become 00000101

i was trying change int to str but it cannot works. here's my code:

def bit8(input):
    print(input)
    y = str(input)
    print(y)

    index = 0

    for index, a in enumerate(y):
        y[index] = a + "0"

    return y[index]

input will contains with array [101, 1101, 11001] and it will become ["00000101", "00001101", "00011001"] the idea is i will split them and i will add "0" and save it again to new array

but i don't know how exactly to do it. please help me


Solution

  • You can simply try format

    l =[101, 1101, 11001]
    
    c = "{:08d}".format
    print([c(item) for item in l])
    

    output #

    ['00000101', '00001101', '00011001']
    

    As a function

    def bit8(input):
        c = "{:08d}".format
        ou=([c(item) for item in input])
    
        return ou
    

    Driver code

    print(bit8(l))
    

    zfill also works

    l =[101, 1101, 11001]
    
    
    def bit8(input):
        ou2=[str(i).zfill(8) for i in input]
        return ou2
    

    Driver code #

    print(bit8(l))
    

    output for zfill method #

    ['00000101', '00001101', '00011001']