Append string to bytearray

yak picture yak · May 18, 2017 · Viewed 9.9k times · Source

I have a byte array, arr and a hexadecimal number a:

arr = bytearray()
a = 'FE'

How can I append this number to bytearray to have the same value, FE? I tried with print(int(a, 16)), but it seems to be a bad idea (it prints 254 instead of FE).

Answer

MSeifert picture MSeifert · May 18, 2017

The 254 is correct because 'FE' is hexadecimal for 254: F = 15, E = 14: 15 * 16**1 + 14 * 16**0 = 254

But if you want to append the characters you could use extend:

>>> arr = bytearray()
>>> arr.extend('FE'.encode('latin-1'))  # you can also choose a different encoding...
>>> arr
bytearray(b'FE')