0

I trying to convert string to Binary and I think I'm not making the proper use of binascii. Bellow is my code:

import binascii
name = 'Bruno'
for c in name:
    print ("The Binary value of '" + c +"' is", binascii.a2b_uu(c))

The result is not what I expected, as you can see below:

The Binary value of 'B' is b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
The Binary value of 'r' is b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
The Binary value of 'u' is b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
The Binary value of 'n' is b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
The Binary value of 'o' is b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

What do I need to change to get the binary value in 0s and 1s?

Izaak van Dongen
  • 2,450
  • 13
  • 23

1 Answers1

0

If what you're looking for is a paintbrush, binascii is a sledgehammer. This is just completely not the tool for what you're trying to do. You can get the code point of a character using the ord function, and there are every so many ways of converting an integer to binary. Here's one way to go about it:

def ascii_name(name):
    for c in name:
        print("The binary value of {} is {:08b}".format(c, ord(c)))

ascii_name("Bruno")

with output

The binary value of B is 01000010
The binary value of r is 01110010
The binary value of u is 01110101
The binary value of n is 01101110
The binary value of o is 01101111

See this question for more detail, and some other approaches. Some of these approaches do use binascii, although unless you're being forced to use binascii I would again urge you not to worry about it.

Izaak van Dongen
  • 2,450
  • 13
  • 23