Harry
Harry

Reputation: 13329

Hex to int32 Big Endian

I am trying to convert this hex to the correct INT32 Big Endian that would be:

ffd7c477 --> -2636681

I checked how it should look here:

http://www.scadacore.com/tools/programming-calculators/online-hex-converter/

I dont know how to convert it. This is where the latitude is

payload = "1901000a03010aff01ff01300a01ffd7c4750016c0540322ed"
latitude = payload[28:36] = ffd7c477 

Here I get the wrong unsigned value:

int(binary[28:36], 16)

Upvotes: 1

Views: 1224

Answers (2)

Georg Grab
Georg Grab

Reputation: 2301

Since Python will use the byteorder of your processor architecture by default to handle numbers (you can check your systems byteorder with sys.byteorder), you'll have to explicitly specify that you want to treat the given value as big endian. The struct module will allow you to do this:

import struct, codecs
val = "ffd7c477"
struct.unpack("!i", codecs.decode(val, "hex"))

The first argument of unpack: ! means to treat the bytes as big endian, i means to treat the bytes as int32 values.

Upvotes: 0

Harry
Harry

Reputation: 13329

This worked struct.unpack('>i', "ffd7c477".decode('hex'))

Upvotes: 1

Related Questions