Reputation: 37
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. Should I still use struct.unpack() if I only need to convert one byte sequence, or should I use int.from_bytes()? I'm just curious to know.
Upvotes: 2
Views: 1684
Reputation: 96172
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
.
Second, struct.unpack
only supports fixed-length numeric C types. int.from_bytes
supports arbitrarily-sized integers (which int
objects are):
>>> 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
. The general purpose of the struct
module is to parse C structs into Python objects.
Upvotes: 4