3

I'm using the answer i saw here.

My function is

def to_bin(s):
    return ' '.join(format(x, 'b') for x in bytearray(s))

It was working really well until i tried to convert a '%' character, i get the output :

>>>to_bin('%')
'100101'

while my expected result is :

>>>to_bin('%')
'0100101'

Do any of you have a solution ?

Thanks in advance.

AntoineLB
  • 482
  • 3
  • 19

1 Answers1

4

Just change your format specifier to pad with zeros to seven characters:

def to_bin(s): 
    return ' '.join(format(x, '07b') for x in bytearray(s))
tttapa
  • 1,397
  • 12
  • 26