Member Avatar for apeiron27

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:)

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.

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

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

It doesn't work either, think again Tony.

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.