how to convert string to byte without encoding python

Solutions on MaxInterview for how to convert string to byte without encoding python by the best coders in the world

showing results for - "how to convert string to byte without encoding python"
Lucia
20 Nov 2016
1import struct
2
3def rawbytes(s):
4    """Convert a string to raw bytes without encoding"""
5    outlist = []
6    for cp in s:
7        num = ord(cp)
8        if num < 255:
9            outlist.append(struct.pack('B', num))
10        elif num < 65535:
11            outlist.append(struct.pack('>H', num))
12        else:
13            b = (num & 0xFF0000) >> 16
14            H = num & 0xFFFF
15            outlist.append(struct.pack('>bH', b, H))
16    return b''.join(outlist)
17
Lynne
01 Feb 2019
1>>> message = 'test 112 hello: what?!'
2>>> message = message.encode('iso-8859-15')
3>>> message 
4b'test 112 hello: what?!'
5