Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append string to bytearray

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).

like image 688
yak Avatar asked Oct 17 '22 12:10

yak


1 Answers

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')
like image 56
MSeifert Avatar answered Oct 20 '22 09:10

MSeifert