Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a MAC number to MAC string?

Tags:

python

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?

like image 767
Bruce Avatar asked Jan 26 '12 15:01

Bruce


People also ask

How do I convert my MAC address to a decimal?

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!

Can you convert MAC address to IP?

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 .

How many digits is a MAC number?

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.


4 Answers

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'
like image 126
Josh Lee Avatar answered Oct 11 '22 23:10

Josh Lee


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'
like image 22
unutbu Avatar answered Oct 11 '22 23:10

unutbu


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)])
like image 37
Michael Mior Avatar answered Oct 11 '22 23:10

Michael Mior


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'
like image 21
Steven Rumbalski Avatar answered Oct 11 '22 22:10

Steven Rumbalski