Python Forum
Value error when converting hex value to bytearray - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Value error when converting hex value to bytearray (/thread-16464.html)



Value error when converting hex value to bytearray - shubhamjainj - Mar-01-2019

Hi,
I am getting ValueError: non-hexadecimal number found in fromhex() arg at position 7.
Below is the code :
Cmd1 = bytearray.fromhex("08 22 1 0 1 0 D4");

Please let me know how to solve this issue


RE: Value error when converting hex value to bytearray - ichabod801 - Mar-01-2019

It's expecting (hexpecting?) two-digit hex numbers.


RE: Value error when converting hex value to bytearray - shubhamjainj - Mar-01-2019

Ok Thanks, will check


RE: Value error when converting hex value to bytearray - DeaD_EyE - Mar-01-2019

input_hex = '08 22 1 0 1 0 D4'

# you can strip the white spaces, but the number of hex values have to be even.
data = bytearray.fromhex(input_hex.replace(' ', ''))
print(data)
Output:
bytearray(b'\x08"\x10\x10\xd4')
If you are using groups, you have to be consistent. Always two hex values have to be grouped together, if white space is used.


RE: Value error when converting hex value to bytearray - Skaperen - Mar-19-2023

i get the same result and wonder where the "22" ended up. i take out the "22" and still get that same result.
Output:
>>> input_hex = '08 1 0 1 0 D4' >>> data = bytearray.fromhex(input_hex.replace(' ', '')) >>> print(data) bytearray(b'\x08\x10\x10\xd4') >>>



RE: Value error when converting hex value to bytearray - deanhystad - Mar-20-2023

You are responding ro a 4 year old thread. But to answer your question, 0x22 == ord('"'). If you look closely you wil see the 22 is not left out, it is printed as a double quote.


RE: Value error when converting hex value to bytearray - DeaD_EyE - Mar-20-2023

broken_input_hex = "08 1 0 1 0 D4"
data = bytes(int(hex_val, 16) for hex_val in broken_input_hex.split())
I think, the name of the broken_input_hex gives a hit, what's wrong.


RE: Value error when converting hex value to bytearray - Skaperen - Mar-20-2023

is responding to an old thread that is still opened a bad thing? i can understand not noticing a " in the result being a bad thing. i'll blame the font my xterm uses for that. the " was actually hard to see. but i was not looking at it for 4 years. i think threads should be auto-closed after 6 months of no activity. but, that's just an opinion, not worth the bytes that encode it.