Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python. Print mac address out of 6 byte string

I have mac address in 6 byte string. How would you print it in "human" readable format?

Thanks

like image 725
PSS Avatar asked Feb 10 '11 16:02

PSS


4 Answers

import struct
"%x:%x:%x:%x:%x:%x" % struct.unpack("BBBBBB",your_variable_with_mac)
like image 189
Jiri Avatar answered Oct 21 '22 03:10

Jiri


There's no need to use struct:

def prettify(mac_string):
    return ':'.join('%02x' % ord(b) for b in mac_string)

Although if mac_string is a bytearray (or bytes in Python 3), which is a more natural choice than a string given the nature of the data, then you also won't need the ord function.

Example usage:

>>> prettify(b'5e\x21\x00r3')
'35:65:21:00:72:33'
like image 35
Scott Griffiths Avatar answered Oct 21 '22 04:10

Scott Griffiths


In Python 3.8 and above, you can just use bytes.hex.

b'\x85n:\xfaGk'.hex(":") // -> '85:6e:3a:fa:47:6b'
like image 5
JojOatXGME Avatar answered Oct 21 '22 04:10

JojOatXGME


Try,

for b in addr:
    print("%02x:" % (b))

Where addr is your byte array.

like image 3
Pablo Santa Cruz Avatar answered Oct 21 '22 04:10

Pablo Santa Cruz