在将十六进制字符串转换为float时,我怎么知道在struct.unpack()中使用哪个endian?
我具有十六进制字符串形式的数据,并将其转换为float,因为
import struct, binascii
a = '0X437A1AF6'
x = struct.unpack('>f', binascii.unhexlify(str(a)[2:]))
print(x[0])
我得到了正确的结果,但是我如何证明使用大端'> f'是正确的选择,或者我如何确定一般使用的endian?试用错误是一个选择,但其他选择是什么?
I have data in form of hexadecimal string and I convert it to float as:
import struct, binascii
a = '0X437A1AF6'
x = struct.unpack('>f', binascii.unhexlify(str(a)[2:]))
print(x[0])
I get the right result but How do I prove that using big endian '>f' is right choice or how do I determine what endian to use in general? Trial an error is one option but what are other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
endianness是对象中的字节的排序方式。我知道您在代码中使用了浮子,但是为简单起见,我在这里使用整数。
Big Endian意味着字节是最大到最小的订购的:
437a1af6
在内存中的意思是43 7a 1a F6
,或1132075766
。Little Endian表示字节是最小到最大的:
437A1AF6
在内存中的意思是f6 1a 7a 43
,或-166036925
(当签名或4128930371
在未签名时)。浮点也具有特定的字节顺序,请参见在这里。末端性会影响浮点表示的字节顺序,并且可以大大更改返回的值。
只要您保持一致,您使用的endian都不会真正重要,但是在当前的X86实现中,Little Endian更常用。没有正确或错误的选择。
就您而言,Little Endian向
-7.832944125711889E+32
和250.10531616210938
的大型解开。Endianness is how the bytes in the object are ordered. I know that you used floats in your code, but I'm using integers here for simplicity.
Big endian means that the bytes are ordered largest-to-smallest:
437a1af6
in memory would mean43 7a 1a f6
, or1132075766
.Little endian means that the bytes are ordered smallest-to-largest:
437a1af6
in memory would meanf6 1a 7a 43
, or-166036925
(when signed, or4128930371
when unsigned).Floating point has a specific byte ordering as well, see here. The endianness affects the byte order of the floating point representation, and it can drastically change the value that is returned.
Whichever endian you use doesn't really matter as long as you stay consistent, but in current x86 implementations, little endian is more commonly used. There is no right or wrong choice.
In your case, little endian unpacks to
-7.832944125711889e+32
and big unpacks to250.10531616210938
.