0

i imported struct module and packed my integer data with '<I'

do my packed data still retain their number characteristics?

i only need to do booliean check comparing two numbers in packed form like a>b or a=b stuff like that.

i did couple of tests and it seems to work fine but i don't wanna take any chances:)

3
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by pyTony
0

No it doesn't work:

>>> a = pack('<I', 3)
>>> b = pack('<I', 257)
>>> a
'\x03\x00\x00\x00'
>>> b
'\x01\x01\x00\x00'
>>> a < b
False

pack() returns strings, which are compared in lexicographical order. == tests should work.

Edited by Gribouillis: n/a

0

Of course then

>>> a[::-1] < b[::-1]
True
>>>

But it is questionable if this is faster than simply unpacking them before compare:

>>> def less_packed(a,b):
	return unpack('<I', a) < unpack('<I', b)

>>> less_packed(a,b)
True
0

Of course then >>> a[::-1] < b[::-1]

It doesn't work either, think again Tony.

Edited by Gribouillis: n/a

0

Oh, you are right, negative numbers are two's complement, which does not order correctly. For unsigned it should be OK.

from struct import pack
for i in range(100000):
	a, b = random.randint(0, 1600), random.randint(0, 2000)
	pa, pb = pack('<I', a), pack('<I', b)
	if (pa[::-1] <  pb[::-1]) != (a < b):
		print pa, pb, a, b
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.