Skip to content Skip to sidebar Skip to footer

How To Convert A Mac Number To Mac String?

I want to convert a MAC address 00163e2fbab7 (stored as a string) to its string representation 00:16:3e:2f:ba:b7. What is the easiest way to do this?

Solution 1:

Use a completely circuitous method to take advantage of an existing function that groups two hex characters at a time:

>>> ':'.join(s.encode('hex') for s in'00163e2fbab7'.decode('hex'))
'00:16:3e:2f:ba:b7'

Updated for Python 3:

>>> ':'.join(format(s, '02x') for s inbytes.fromhex('00163e2fbab7'))
'00:16:3e:2f:ba:b7'

Solution 2:

Using the grouper idiomzip(*[iter(s)]*n):

In [32]: addr = '00163e2fbab7'

In [33]: ':'.join(''.join(pair) for pair in zip(*[iter(addr)]*2))
Out[33]: '00:16:3e:2f:ba:b7'

Also possible, (and, in fact, a bit quicker):

In [36]: ':'.join(addr[i:i+2] for i in range(0,len(addr),2))
Out[36]: '00:16:3e:2f:ba:b7'

Solution 3:

If you have a string s that you want to join with colons, this should do the trick.

':'.join([s[i]+s[i+1] for i inrange(0,12,2)])

Solution 4:

If you are addicted to regular expressions you could try this unpythonic approach:

>>>import re>>>s = '00163e2fbab7'>>>':'.join(re.findall('..', s))
'00:16:3e:2f:ba:b7'

Solution 5:

> Works well with python 3

ap_mac = b'\xfe\xdc\xba\xab\xcd\xef'
decoded_mac = hexlify(ap_mac).decode('ascii')
formatted_mac = re.sub(r'(.{2})(?!$)', r'\1:', decoded_mac)

Post a Comment for "How To Convert A Mac Number To Mac String?"