Reputation: 107
I have a string in Python containing some hexa information (length 256) as follows:
Str0 = '04008020546c359986812644420e453113e209afeaaeeb316f3a07000000000000000000b8fa13b3fca087c1456daac626ab9b8a47eae821a326f17e0ffffc15433df709b0f718610b1812175a5c9544800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000280'
This string is Hex and we need to create a byte string using it. Then print one byte (its numeric value) for each new line.
I thought this would work but it doesn't:
bytes_object = bytes.fromhex(Str0)
ascii_string = bytes_object.decode('ASCII')
The error thrown is: 'ascii' codec can't decode byte 0x80 in position 2: ordinal not in range(128)
Upvotes: 0
Views: 950
Reputation: 316
The first line: bytes_object = bytes.fromhex(Str0)
gives you a bytes type that functions as raw bytes data / byte array.
to print the numeric value of each byte, what you need to do is:
for x in bytes_object : print(x)
If you want an array of the numeric values you can use [int(x) for x in bytes_object]
Upvotes: 1
Reputation: 4512
In hex, every 2 characters represents a byte. So from your hex string, the corresponding bytes would be:
0: 0x04 (decimal: 4)
1: 0x00 (decimal: 0)
2: 0x80 (decimal: 128)
3: 0x20 (decimal: 32)
... etc.
Converting this string to bytes is fine, since a byte can have any value from 0 - 255.
The problem is where you're trying to decode it as ASCII. If you look at an ASCII table, you'll see that the maximum value in the table is 127 (0x7F). The byte at position [2] that you're trying to decode has a hex value of 0x80 (decimal value of 128), which isn't a valid ASCII character.
So, the question is, where did your original hex string come from, and what makes you think it represents valid ASCII characters?
Upvotes: 0