rjani1
rjani1

Reputation: 17

Forming a byte string in Python

I am creating a method in Python whereby it will take a number which will form a byte string that will then get sent to the Arduino. However whenever I try, the escape character is always included in the final byte string.

Here is the snippet of the code I am using:

num = 5
my_str = '\\x4' + str(num)
my_str.encode('utf-8')

Result:

b'\\x45'

I tried another 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 a different way:

num = 5
u = chr(92) + 'x4' + str(num)
u.encode('ISO-8859-1')

Result:

b'\\x45'

I would like to get the byte string to be b'\x45' without the escape character but not really sure what I have missed. I will appreciate any pointers on how I can achieve this.

Upvotes: 0

Views: 463

Answers (2)

Izaak van Dongen
Izaak van Dongen

Reputation: 2545

Your problem is that you have already escaped the backslash. It is not recommended to construct a literal using an unknown variable, especially if there's a simpler way, which there is:

def make_into_bytes(n):
    return bytes([64 + n])

print(make_into_bytes(5))

This outputs

b'E'

Note that this isn't a bug, as this is simply the value of 0x45:

>>> b'\x45'
b'E'

The way this function works is basically just doing it by hand. Prepending '4' to a hex string (of length 1) is the same as adding 4 * 16 to it, which is 64. I then construct a bytes object out of this. Note that I assume n is an integer, as in your code. If n should be a digit like 'a', this would be the integer 10.

If you want it to work on hex digits, rather than on integer digits, you would need to change it to 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 simply converts the digit from base 16 first.

Upvotes: 4

Sven Marnach
Sven Marnach

Reputation: 601351

You can use the built-in function chr() to convert an integer to the corresponding character:

>>> chr(0x40 + 5)
'E'

Alternatively, if you just one to get the n-th letter of the alphabet, it might be more readable to use str.ascii_uppercase

>>> string.ascii_uppercase[5 - 1]
'E'

Note that the results in this answer are strings in Python 3, not bytes objects. Simply calling .encode() on them will convert them to bytes.

Upvotes: 1

Related Questions