[英]Difference between struct.unpack() and int.from_bytes()?
Is there a difference between the two?两者有区别吗? When should I use one over the other?
我什么时候应该使用其中一种? They do the same thing basically except struct.unpack() works for multiple byte sequences.
它们基本上做同样的事情,除了 struct.unpack() 适用于多个字节序列。 Should I still use struct.unpack() if I only need to convert one byte sequence, or should I use int.from_bytes()?
如果我只需要转换一个字节序列,我还应该使用 struct.unpack(),还是应该使用 int.from_bytes()? I'm just curious to know.
我只是想知道。
Well, for starters, int.from_bytes
will only ever return a single int
object, so if you want to create anything other than an int
, you can't use int.from_bytes
.好吧,对于初学者来说,
int.from_bytes
只会返回一个int
对象,所以如果你想创建除int
以外的任何东西,你就不能使用int.from_bytes
。
Second, struct.unpack
only supports fixed-length numeric C types.其次,
struct.unpack
只支持固定长度的数字 C 类型。 int.from_bytes
supports arbitrarily-sized integers (which int
objects are): int.from_bytes
支持任意大小的整数( int
对象是):
>>> int.from_bytes(b'\xff'*8, 'little')
18446744073709551615
>>> int.from_bytes(b'\xff'*10, 'little')
1208925819614629174706175
>>> int.from_bytes(b'\xff'*100, 'little')
6668014432879854274079851790721257797144758322315908160396257811764037237817632071521432200871554290742929910593433240445888801654119365080363356052330830046095157579514014558463078285911814024728965016135886601981690748037476461291163877375
If you only ever want a single integer, I would probably just use int.from_bytes
.如果您只想要一个整数,我可能只会使用
int.from_bytes
。 The general purpose of the struct
module is to parse C structs into Python objects. struct
模块的一般用途是将 C 结构解析为 Python 对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.