Sarah cartenz
Sarah cartenz

Reputation: 1313

Converting a sub-string of a string into bytes then to integers in python

I have a text file that actually contains hex values stored by a program. For instance the the file.txt would contain:

4D 45 5A 4E 53 41 54

I need to convert the raw data to understand it, specifically I need to take two bytes and convert them into an integer. This is the approach I took:

First I split the text file to an array based on the spaces. Then I converted the array to a byte array.

 beacon = beacon.split()
 beaconBytes = [byte.encode('utf-8') for byte in beacon] 

Now it looks like this:

[b'4D', b'45', b'5A', b'4E', b'53', b'41', b'54']

Since the data is transmitted in little endian, the first two bytes should translate to 0x454d = 17741.

But why does :

 int.from_bytes(beaconBytes[0]+beaconBytes[1], byteorder='little', signed=False)

print 892617780? Where did this huge number come from?

Upvotes: 2

Views: 103

Answers (2)

DYZ
DYZ

Reputation: 57033

encode does not do what you think it does. It merely changes character encodings. You should convert your hexadecimal strings into integers with int:

bytes = [chr(int(x, 16)).encode() for x in beacon.split()]
#[b'M', b'E', b'Z', b'N', b'S', b'A', b'T']
int.from_bytes(bytes[0]+bytes[1], byteorder='little', signed=False)
#17741

Upvotes: 4

Adam.Er8
Adam.Er8

Reputation: 13393

The "bytes" object actually has the value of the CHARS '4', 'D', and so on (which is not the same as the value 4, or 13, or other hex values represented by 0-9A-F).

to convert a hex string to an int value you can simply use int with a base of 16, like this:

beacon = '4D 45 5A 4E 53 41 54'.split()
firstValHexStr = beacon[1]+beacon[0] # 454D
firstValInt = int(firstValHexStr,16)
print(firstValInt)

Output:

17741

No need to go through bytes object at all :)

Upvotes: 4

Related Questions