开发者

Need some help converting a MAC address to binary data for use in an ethernet frame

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 w开发者_StackOverfloworks?


Why do people insist on writing all that?

def mactobinar(mac):
  return binascii.unhexlify(mac.replace(':', ''))


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜