how to convert string to byte without encoding python code example
Example 1: how to convert string to byte without encoding python
>>> message = 'test 112 hello: what?!'
>>> message = message.encode('iso-8859-15')
>>> message
b'test 112 hello: what?!'
Example 2: how to convert string to byte without encoding python
import struct
def rawbytes(s):
"""Convert a string to raw bytes without encoding"""
outlist = []
for cp in s:
num = ord(cp)
if num < 255:
outlist.append(struct.pack('B', num))
elif num < 65535:
outlist.append(struct.pack('>H', num))
else:
b = (num & 0xFF0000) >> 16
H = num & 0xFFFF
outlist.append(struct.pack('>bH', b, H))
return b''.join(outlist)