Beautiful Python

I wrote this line of code last night:

reduce(lambda acc,v: (acc << 8) | (v & 0xff), bytes[::-1])

That takes an array of bytes, reverses it (for CPU endianness), and then builds it into a single integer by ORring each byte together and shifting left 8 bits each time. I use it to convert 16 bytes into a single 128 bit integer. In one line! Imagine how nasty that would be in C (especially a 128 bit integer!)

I find it interesting that I’m now appreciating functional programming idioms. My CS degree really put me off them for a long while: crappy practicals using a crappy ML compiler. I remember it had a dislike for certain whitespace characters; imagine trying to find a whitespace character somewhere in a file with lots of whitespace, when the error messages are never anywhere near where the actual error occurred. Yuck!

Perhaps if I’d done it slightly later and had access to the Harlequin ML tools it would have been a different story.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: