unsigned 32 bit arithmetic type?

Robin Becker robin at reportlab.com
Wed Oct 25 12:25:32 EDT 2006


Paul Rubin wrote:
> Robin Becker <robin at reportlab.com> writes:
>>> type(nx.array([1,2,3],dtype=nx.uint32)[0])
>>> <type 'numpy.uint32'>
>> great, but do we have a pure python version?
> 
> array.array('L', [1,2,3])
yes that works if @L is unsigned 32 bit. I guess >L is always 4 bytes. Part of 
my confusion comes from not realizing all the different 64 bit models. In python 
I can get away with the following

	def add32(x, y):
		"Calculate (x + y) modulo 2**32"
		return ((x&0xFFFFFFFFL)+(y&0xFFFFFFFFL)) & 0xffffffffL

	def calcChecksum(data):
		"""Calculates TTF-style checksums"""
		if len(data)&3: data = data + (4-(len(data)&3))*"\0"
		sum = 0
		for n in unpack(">%dl" % (len(data)>>2), data):
			sum = add32(sum,n)
		return sum

but my tests sometimes look a bit odd.

eg
	self.assertEquals(add32(10, -6), 4)
	self.assertEquals(add32(6, -10), -4&0xFFFFFFFFL)
	self.assertEquals(add32(0x80000000L, -1), 0x7FFFFFFF)
	self.assertEquals(add32(0x7FFFFFFF, 1), 0x80000000L)

-- 
Robin Becker




More information about the Python-list mailing list