def to_binary(self, message):
'''
Given a text message, returns a binary string (still represented as a
character string).
'''
# All spaces are encoded as null bytes:
message = message.replace(self.SILENCE_TOKEN, self.SILENCE_ENCODING)
# handle unicode
message = codecs.encode(message, 'utf-8')
data = []
for c in message:
# get the numeric value of the character
try:
c = ord(c)
except TypeError:
# already an int (Python 3)
pass
# convert to binary
bin_c = bin(c)
# remove the '0b' prefix
bin_c = bin_c[2:]
# pad with zeros
bin_c = bin_c.zfill(8)
data.append(bin_c)
return ''.join(data)
评论列表
文章目录