简体   繁体   English

Python struct.error: integer 超出“q”格式代码的范围

[英]Python struct.error: integer out of range for 'q' format code

I'm having a problem, I want to cast a binary number into a double precission number.我有一个问题,我想将二进制数转换为双精度数。

After some searchs, I found some way, but I'm still having a problem, I can cast "little" numbers but not the big ones (double precission), here's my example code:经过一番搜索,我找到了一些方法,但我仍然遇到问题,我可以投射“小”数字但不能投射大数字(双精度),这是我的示例代码:

print unpack( "d", pack( "q", 4631069437225598976 ) )[ 0 ]
print unpack( "d", pack( "q", 13829563286724542464 ) )[ 0 ]

The first one has no problem, but the next one crashes with the error on the description.第一个没有问题,但下一个因描述错误而崩溃。

The first number should be: 41.7274732 And the second one should be: -0.8899581第一个数字应该是:41.7274732 第二个应该是:-0.8899581

Any idea?任何想法?

Thanks a lot非常感谢

Using Q for unsigned long long, instead of q for long long, will give the output you want: 使用Q表示无符号long long,而不是q表示long long,将得到所需的输出:

from struct import pack, unpack

print unpack( "d", pack( "Q", 4631069437225598976 ) )[ 0 ]
print unpack( "d", pack( "Q", 13829563286724542464 ) )[ 0 ]

outputs: 输出:

41.7274742126
-0.889958143234

Edit: 编辑:

please check carefully with your other big numbers because it might give the same error, we are just adding one bit in the most signicant bit position. 请仔细检查您的其他大数字,因为它可能会给出相同的错误,我们只是在最高位位置加一位。

Consider reviewing the range for the format applicable to the data you're using.考虑查看适用于您正在使用的数据的格式的范围。 I had a similar problem packing a positive 4 byte number as signed that was larger than 2147483647. Changing the format to unsigned allowed for inputs up to 4294967295 (packed as b'\xff\xff\xff\xff').我在打包一个大于 2147483647 的带符号正 4 字节数时遇到了类似的问题。将格式更改为无符号允许输入高达 4294967295(打包为 b'\xff\xff\xff\xff')。

From Python struct.pack() article on dqdongg.com and this comment on pyinstaller's github I found the references needed to change the expected format for the data I was packing.dqdongg.com 上的 Python struct.pack() 文章对 pyinstaller 的 github 的评论中,我找到了更改预期格式所需的数据的打包参考。 The error message in this related question about format ranges would've been more helpful to understand the problem I was having, instead of "struct.error: argument out of range".这个关于格式范围的相关问题中的错误消息将更有助于理解我遇到的问题,而不是“struct.error:参数超出范围”。

Format Type Quick Guide格式类型快速指南

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

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