Why does python change its value when reading binary data?

Asked 2 years ago, Updated 2 years ago, 23 views

If you open it in a binary editor, you will see the following data:

0000B D7 150 04 04 38 00 13 E8000
~ hereinafter abbreviated

If you try to read the file and retrieve the data using the following code:
The value was slightly different, and the top 38 was 8.

f=open(inputfiles, "rb")
f.read(40)

0000B D7 150 04 04 08 00 13 E8000

It seems that the value has changed after loading in several other places.

It's called win format which is used for variable length earthquakes.
I am troubled because the value has changed in the middle of loading.
How can I load it with the original value?

python

2022-09-30 19:26

3 Answers

It's the 9th byte from the beginning of the read data.

>>f=open(inputfiles, "rb")
>> data=f.read(40)
>> data [8]
'8'

The data will remain '0x38'.

>>hex(ord(data[8]))
'0x38'

The hexadecimal 38 was ASCII '8', so you misunderstood Python's display in the interactive shell (as others answered)

>>hex(ord('\x38'))
'0x38'
>>hex(ord('8'))
'0x38'

This is because Python 2 handles the byte column or the string (non-Unicode character) because it is str type and interprets the data as characters when displaying the str type on the screen.The value on the memory is 0x38, so you can use a different method (like someone else's answer) only when you print on the screen.


2022-09-30 19:26

I'm not sure how I checked the value, but 0x38 is ASCII and "8".As for the data, I read 0x38, but in the process of checking the contents, it was displayed and interpreted as characters, so it was just "8".


2022-09-30 19:26

How do you process and confirm the result of read()?

data=f.read(40)
    print ['0x%x'%ord(x) for x indata ]

Is 38 really 8? 0x38 is an ascii code of "8", so it just looks like you're mistaken

data=bytearray(f.read(40))

and byte array so that the input can be processed as a byte column. Unfortunately, "b" in open() does not mean "handle the result of read() as a byte column."


2022-09-30 19:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.