简体   繁体   English

如何在python十六进制字符串中重新排序字节并转换为long

[英]how to re-order bytes in a python hex string and convert to long

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. 我有这个长十六进制字符串20D788028A4B59FB3C07050E2F30在python 2.7中我想提取前4个字节,更改它们的顺序,将其转换为有符号数,将其除以2 ^ 20然后将其打印出来。 In C this would be very easy for me :) but here I'm a little stuck. 在C中这对我来说很容易:)但在这里我有点卡住了。

For example the correct answer would extract the 4 byte number from the string above as 0x288D720. 例如,正确的答案将从上面的字符串中提取4字节数作为0x288D720。 Then divided by 2^20 would be 40.5525. 然后除以2 ^ 20将是40.5525。 Mainly I'm having trouble figuring out the right way to do byte manipulation in python. 主要是我在找出在python中进行字节操作的正确方法时遇到了麻烦。 In CI would just grab pointers to each byte and shift them where I wanted them to go and cast into an int or a long. 在CI中,只需获取指向每个字节的指针,并将它们移动到我希望它们转移到int或long的位置。

Python is great in strings, so let's use what we have: Python在字符串方面很棒,所以让我们使用我们拥有的东西:

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... 但是除以 2 ** 20对位有点奇怪,所以也许转移至少值得一提......

print int(t, 16) >> 20

After all, I would 毕竟,我愿意

print int(t, 16) * 1.0 / (1 << 20)

For an extraction you can just do foo[:8] 对于提取你可以做foo[:8]

Hex to bytes: hexadecimal string to byte array in python 十六进制到字节: python中的十六进制字符串到字节数组

Rearrange bytes: byte reverse AB CD to CD AB with python 重新排列字节: 字节反向AB CD到CD AB与python

You can use struct for conversion to long 您可以使用struct进行转换

And just do a normal division by (2**20) 并按(2**20)进行正常除法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM