-1

I'm attempting to create a binary file from a python script using Python 2.7. Whenever I try converting my strings into a binary string and print it to see if it converted, it just shows the (ascii) string. Is that because print will always show the ascii equivalent and not the binary even if it is binary encoded?

EX.

my_string = "Testing binary string conversion"
bin_string = str.encode(my_string, "UTF-8")
print bin_string
Snake
  • 3
  • 3

2 Answers2

0

UTF-8 is a character encoding capable of encoding all possible characters, or code points, in Unicode. The encoding is variable-length and uses 8-bit code units. It was designed for backward compatibility with ASCII, and to avoid the complications of endianness and byte order marks in the alternative UTF-16 and UTF-32 encodings. The name is derived from: Universal Coded Character Set + Transformation Format—8-bit.

From Wikipedia.org. And this explains why you see the same thing printed (because the unicode version is the same!), even repr should give you the same result.

To convert your string to binary you can refer to this detailed answer by Sebastian few years ago.

Hope this answer clears your doubts...

Community
  • 1
  • 1
Andrew
  • 140
  • 10
0
import binascii


text = "Testing binary string conversion"
byte = text.encode()
hexadecimal = binascii.hexlify(byte)
decimal = int(hexadecimal, 16)
binary = bin(decimal)[2:].zfill(8)
print("hex: %s, decimal: %s, binary: %s" % (hexadecimal, decimal, binary))