X21
X21

Reputation: 168

Encoding method in python not working

Got a problem with encoding process.

      def str2bin(message):
          binary = bin(int(binascii.hexlify(message), 16))
          return binary[2:]

The error is :

binary = bin(int(binascii.hexlify(message), 16)) TypeError: a bytes-like object is required, not 'str'

I'm trying to type only ascii in a program. What is causing the error?

Upvotes: 0

Views: 315

Answers (1)

Mike Scotty
Mike Scotty

Reputation: 10782

You need to encode the string, either in your function or before you pass it to your function:

import binascii

def str2bin(message):
    binary = bin(int(binascii.hexlify(message.encode("ascii")), 16))
    return binary[2:]

print(str2bin("X")) # 1011000

The reason is, that hexlify expects a data type that supports the buffer interface.

A bytes-like object does, a str does not.

See also the note on the binascii docs:

a2b_* functions accept Unicode strings containing only ASCII characters. Other functions only accept bytes-like objects (such as bytes, bytearray and other objects that support the buffer protocol).

Upvotes: 2

Related Questions