I have mac address in 6 byte string. How would you print it in "human" readable format?
Thanks
import struct
"%x:%x:%x:%x:%x:%x" % struct.unpack("BBBBBB",your_variable_with_mac)
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'
在Python 3.8及更高版本中,您可以只使用bytes.hex
。
b'\x85n:\xfaGk'.hex(":") // -> '85:6e:3a:fa:47:6b'
Try,
for b in addr:
print("%02x:" % (b))
Where addr is your byte array.
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)
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.