pythonnetwork-programmingpython-3.xpython-2.7arrays

MAC address conversion into byte array in python


I have a mac address in this format

00:45:36:45:f2:00  

I want to convert this mac address into byte array. I mean, by removing the ':' in between, I get total of 6 bytes and those 6 bytes should sit as six bytes in a byte array. And how is that byte array converted into an integer? Is there any in-built function in python that would do that with very very less execution time(like in microseconds)?


Solution

  • In Python 2.7,

    macstr = addr.replace(':', '').decode('hex')
    

    In Python 3,

    import binascii
    macbytes = binascii.unhexlify(addr.replace(b':', b''))