pythonpython-bytearray

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


Solution

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