I discover (using Thonny) for it to accept a hex number in my .py code I need to use 0x and not \x, but then when the results are shown in the Shell, it shows the same number but with the \x prefix.
So I try this in the Shell
Code: Select all
>>> int("\xc0",16)
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
ValueError: invalid literal for int() with base 16: 'À'
so I try this in the Shell
Code: Select all
>>> int("0xc0",16)
192
My next puzzle relates to how to get the hex numbers I extract from a file into decimal. I set the file up as binary, used read(2) to get at two hex numbers, that seems to work thus:
Code: Select all
position = fo.seek(0x0C,0) # put pointer to 12
my_bpm = fo.read(2)
print("Look now at BPM as two hx numbers ", my_bpm)
Code: Select all
Look now at BPM as two hx numbers b'\x03\xc0'
And now to the big puzzle, exactly what data type is my_bpm returned when using the read() function? As string?
So I use
Code: Select all
my_bpm_number = int(my_bpm, 16)
print("BPM from hex to decimal - ", str(my_bpm_number) )
I want to print the number so I can inspect it so I convert the number to a string for printing, but alas errors.
Code: Select all
Look now at BPM as two hx numbers b'\x03\xc0'
Traceback (most recent call last):
File "/home/pi/tester_1/File_Handling/file_experiments_1.py", line 21, in <module>
my_bpm_number = int(my_bpm, 16)
ValueError: invalid literal for int() with base 16: b'\x03\xc0'
My objective is simply to extract 2 adjacent hex numbers from a binary file and use the resulting (decimal) number in further number munching.