views:

42

answers:

3

I've been looking over various internet postings and a lot of the code I've seen looks similar to this:

def mactobinar(mac):
    addr = ''
    temp = mac.replace(':', '')

    for i in range(0, len(temp), 2):
        addr = ''.join([addr, struct.pack('B', int(temp[i: i + 2], 16)))])

    return addr

Can someone explain how this code works?

+2  A: 

Why do people insist on writing all that?

def mactobinar(mac):
  return binascii.unhexlify(mac.replace(':', ''))
Ignacio Vazquez-Abrams
Why do people insist on writing all that? def mactobinary(mac): return mac.replace(':', '').decode('hex') ;)
Jean-Paul Calderone
The `hex` codec goes away in 3.x.
Ignacio Vazquez-Abrams
+1  A: 

7.3. struct — Interpret strings as packed binary data. That'd be a good place to start.

Matthew Iselin
A: 

Ok im not really the best at pythen but ill give it a shot.

when the mac address is passed into mactobinar the first thing that happens is that your removing the semi colon to make a constant string without any delimiters.

So 01:23:45:67:89:ab becomes 0123456789ab

Ok in the next part were looping threw a range, this range here is creating a offset range.

So range(0, len(temp), 2) returns an array with the ranges like range(start,max,steps);

then for every value in that array were creating a binary for that integer using struct.pack and also joining it together

Your version struct.pack('B', int(temp[i: i + 2], 16)))

Documanted version struct.pack(fmt, v1, v2, ...)

pack converts an entity into its binary format.

hope this gives you some insight on whats going here

Here are some items to get you started:

http://docs.python.org/library/struct.html#format-characters

http://docs.python.org/library/struct.html#struct.pack

RobertPitt