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?
Now, to finally convert the hexadecimal MAC address to a decimal MAC, we need to sum all the individual numbers : 10485760 + 262144 + 45056 + 1024 + 48 + 9 = 10 794 041!
You can also use perfect MAC address converter can convert any MAC address into IPv4 internet protocol address ranges and IPV6 internet protocol address ranges .
The MAC address is a 12 digit hexadecimal number that is most often displayed with a colon or hypen separating every two digits (an octet), making it easier to read. Example: A MAC address of 2c549188c9e3 is typically displayed as 2C:54:91:88:C9:E3 or 2c-54-91-88-c9-e3.
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 in bytes.fromhex('00163e2fbab7'))
'00:16:3e:2f:ba:b7'
Using the grouper idiom zip(*[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'
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 in range(0,12,2)])
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With