从“无符号”值读取 32 位有符号值字节流
我想从一个文件中提取数据,该文件的信息以大端存储并且始终无符号。从unsigned int到int的“cast”如何影响实际的十进制值?我是否正确,最左边的位决定该值是正数还是负数?
我想用 python 解析该文件格式,并且读取和无符号值很容易:
def toU32(bits):
return ord(bits[0]) << 24 | ord(bits[1]) << 16 | ord(bits[2]) << 8 | ord(bits[3])
但是相应的 toS32 函数是什么样子的?
感谢您提供有关 struct 模块的信息。但我仍然对我的实际问题的解决方案感兴趣。
I want to extract data from a file whoose information is stored in big-endian and always unsigned. How does the "cast" from unsigned int to int affect the actual decimal value? Am I correct that the most left bit decides about the whether the value is positive or negative?
I want to parse that file-format with python, and reading and unsigned value is easy:
def toU32(bits):
return ord(bits[0]) << 24 | ord(bits[1]) << 16 | ord(bits[2]) << 8 | ord(bits[3])
but how would the corresponding toS32 function look like?
Thanks for the info about the struct-module. But I am still interested in the solution about my actual question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会使用struct。
格式字符串“>I”表示从字符串位读取大端字节序“>”、无符号整数“I”。对于有符号整数,您可以使用“>i”。
编辑
必须查看另一个StackOverflow答案来记住如何“转换”有符号整数python 中的无符号整数。尽管它不是转换,而是重新解释这些位。
I would use struct.
The format string, ">I", means read a big endian, ">", unsigned integer, "I", from the string bits. For signed integers you can use ">i".
EDIT
Had to look at another StackOverflow answer to remember how to "convert" a signed integer from an unsigned integer in python. Though it is less of a conversion and more of reinterpreting the bits.
我将使用 struct 模块的 打包和解包方法。
有关一些示例,请参阅 Python 中整数的字节序。
I would use the struct module's pack and unpack methods.
See Endianness of integers in Python for some examples.
toS32(bits) 的无条件版本可能类似于:
当然,您也可以预先计算任何其他位大小的掩码。
The non-conditional version of toS32(bits) could be something like:
You can pre-compute the mask for any other bit size too of course.