yak
yak

Reputation: 3940

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

Upvotes: 5

Views: 14729

Answers (1)

MSeifert
MSeifert

Reputation: 152870

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

Upvotes: 5

Related Questions