1

I have this long hex string 20D788028A4B59FB3C07050E2F30 In python 2.7 I want to extract the first 4 bytes, change their order, convert it to a signed number, divide it by 2^20 and then print it out. In C this would be very easy for me :) but here I'm a little stuck.

For example the correct answer would extract the 4 byte number from the string above as 0x288D720. Then divided by 2^20 would be 40.5525. Mainly I'm having trouble figuring out the right way to do byte manipulation in python. In C I would just grab pointers to each byte and shift them where I wanted them to go and cast into an int or a long.

Iron Fist
  • 10,739
  • 2
  • 18
  • 34
confused
  • 713
  • 1
  • 5
  • 16

2 Answers2

2

For an extraction you can just do foo[:8]

Hex to bytes: hexadecimal string to byte array in python

Rearrange bytes: byte reverse AB CD to CD AB with python

You can use struct for conversion to long

And just do a normal division by (2**20)

Community
  • 1
  • 1
Hans
  • 2,354
  • 3
  • 25
  • 35
2

Python is great in strings, so let's use what we have:

s = "20D788028A4B59FB3C07050E2F30"
t = "".join([s[i-2:i] for i in range(8,0,-2)])
print int(t, 16) * 1.0 / pow(2,20)

But dividing by 2**20 comes a bit strange with bits, so maybe shifting is at least worth a mention too...

print int(t, 16) >> 20

After all, I would

print int(t, 16) * 1.0 / (1 << 20)
flaschbier
  • 3,910
  • 2
  • 24
  • 36