8

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

Thanks

1
  • 1
    Perhaps to make it more readable you could actually look up the manufacturer.
    – krs1
    Commented Feb 10, 2011 at 16:27

7 Answers 7

13
import struct
"%x:%x:%x:%x:%x:%x" % struct.unpack("BBBBBB",your_variable_with_mac)
1
  • 3
    You should probably use %02x instead of %x. Otherwise, the preceding 0 is missing for bytes below 16.
    – JojOatXGME
    Commented Dec 29, 2019 at 16:11
12

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'
1
  • 2
    I find b.encode('hex') slightly more readable than '%02x' % ord(b), but the effect is the same.
    – kasperd
    Commented Dec 1, 2018 at 14:03
9

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

b'\x85n:\xfaGk'.hex(":") // -> '85:6e:3a:fa:47:6b'
1
  • 1
    Makes a handy mac address formatter: decimal_mac.to_bytes(6, "big").hex(":") Commented May 7, 2023 at 16:56
3

Try,

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

Where addr is your byte array.

0

s=b'\x04NZ\xdf\x7f\xab'

1) import struct ssid_2 = "%02x:%02x:%02x:%02x:%02x:%02x" % struct.unpack("BBBBBB", s)

or

2) ':'.join(f'{x:02x}' for x in s)

but 1) is way faster than 2)

0

For CircuitPython I used the following:

mac_address = ":".join(f"{byte:02x}" for byte in  wifi.radio.mac_address)
print("My MAC addr:", mac_address)

Here is a blog post showing 5 other methods for converting a MAC address to a human readable format.

-3

Is the usual hex format not human-readable enough? (see this for a way to convert a byte to hex)

de:ad:be:ef:ca:fe

Incidentally, this is the way MAC addresses are displayed in most software (just Windows uses dashes instead of colons).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.