Tue, 18 Mar 2008
Snakes! Snakes!
Some days... I wasted an hour or two today chasing what turned out to be a bug in Python. For a few reasons (lazyness mostly) we're still using Python 2.2 at work. I'd been having fun writing a test script (well, fun...) where I needed to do endianness conversion. Python thoughtfully provides access to the usual ntoh/hton functions, so that's what I used.
import socket aNumber = 0xFFFFFFFF print socket.ntohl(aNumber)
See, really easy. Except it doesn't work, at least not in Python 2.2. As it turns out Python insists on interpreting 'aNumber' as a singled long, which causes it to throw an OverflowError whenever you input (or end up) with something that has the MSB set.
As I couldn't easily upgrade Python I worked around it. I hope no children read this as this could scar them for life.
import socket def myntohl(input): if input & 0x80000000: input = input & 0x7FFFFFFF input = socket.ntohl(input) input = input | 0x80 else: input = socket.ntohl(input) return input
Don't worry, it's fixed from 2.3 onwards.
posted at: 21:34 | path: / | [ 0 comments ]