Forming a byte string in Python -
i creating method in python whereby take number form byte string sent arduino. whenever try, escape character included in final byte string.
here snippet of code using:
num = 5 my_str = '\\x4' + str(num) my_str.encode('utf-8')
result:
b'\\x45'
i tried method:
num2 = 5 byte1 = b'\\x4' byte2 = bytes(str(num2), 'iso-8859-1') new_byte = byte1 + byte2 new_byte
result:
b'\\x45'
trying yet in different way:
num = 5 u = chr(92) + 'x4' + str(num) u.encode('iso-8859-1')
result:
b'\\x45'
i byte string b'\x45' without escape character not sure have missed. appreciate pointers on how can achieve this.
your problem have escaped backslash. not recommended construct literal using unknown variable, if there's simpler way, there is:
def make_into_bytes(n): return bytes([64 + n]) print(make_into_bytes(5))
this outputs
b'e'
note isn't bug, value of 0x45:
>>> b'\x45' b'e'
the way function works doing hand. prepending '4' hex string (of length 1) same adding 4 * 16 it, 64. construct bytes object out of this. note assume n integer, in code. if n should digit 'a'
, integer 10
.
if want work on hex digits, rather on integer digits, need change this:
def make_into_bytes(n): return bytes([64 + int(n, 16)]) print(make_into_bytes('5')) print(make_into_bytes('a'))
with output
b'e' b'j'
this quite converts digit base 16 first.
Comments
Post a Comment