5

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
yak
  • 3,770
  • 19
  • 60
  • 111
  • Possible duplicate of [Iron python: How to append string to bytearray](http://stackoverflow.com/questions/22656250/iron-python-how-to-append-string-to-bytearray) – Chanda Korat May 18 '17 at 12:01
  • Everything is correct - you parse the hex value using `int` into an integer and then `print` outputs the decimal representation. `FE` in hex is `254` in dec. Just use `arr.append(int(a, 16))` and everything will be correct. Or you want to append it as a string, like two characters? – Eswcvlad May 18 '17 at 12:02
  • @Eswcvlad: If `FE` is `254` that's fine. I forgot to recalculate this. So it seems ok now. Thanks! – yak May 18 '17 at 12:08

1 Answers1

3

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')
MSeifert
  • 145,886
  • 38
  • 333
  • 352