Home > OS >  how to make binary to bit 8 in python
how to make binary to bit 8 in python

Time:11-03

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

CodePudding user response:

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']

CodePudding user response:

Maybe you want to use XOR directly and convert your input instead:

a = [101, 1101, 11001]

def toBinary (s):
    return int(str(s), base=2)

def toStringInteger (s):
    return int(f'{s:08b}')

a_int = [toBinary(s) for s in a]
# a_int is now [5, 13, 25]

# XOR with 11111 (^ is the XOR operator)
xored_int = [e ^ 0b11111 for e in a_int]
xored = [toStringInteger(s) for s in xored_int]

# Printing the XOR value
print(f"{a} XOR 11111 is {xored}")
>>> [101, 1101, 11001] XOR 11111 is [11010, 10010, 110]
  • Related