Question

I had to write a script that generates some fixture file with increasing fake MAC addresses.

To do that, I decided to have some fun and try to make it as compact as I could. I ended up with:

def mac_address(i):
    return ':'.join(['%02x'] * 6) % tuple([(i >> (8 * j)) & 0xFF for j in reversed(range(6))])

Which actually works pretty well. Obviously, writing this that way is the best way to get slapped by the future person that must work on it, but I did it for the fun (and wrote a more readable version in comment).

But now I'm curious, can you think of any more compact way of writing that ? (That is without removing the spaces).

Was it helpful?

Solution

What about

':'.join('%02x' % (i>>(8*j) & 0xFF) for j in reversed(range(6)))

That is more compact and easier to understand.

OTHER TIPS

def mac_address(i):
    return ':'.join(a+b for a, b in zip(*[iter('{:012x}'.format(i))]*2))

The first step is to get a hex string zero filled so that it is exactly 12 digits, which is what '{:012x}'.format(i) does. Then we break that string up in two-character chunks using the method of grouping items from the zip() documentation, and join the result on ':'.

Maybe:

from struct import pack, unpack
def mac_address(i):
    return ":".join(["%02x"] * 6) % unpack("BBBBBB", pack("!Q", i)[2:])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top