Python - 統計MAC地址

字符串之間是無法直接進行加法運算的,要先經過轉換。

十六進制字符串轉換爲十進制

int('a',16)

int('0xa',16)


十進制轉換爲十六進制

hex(10)

'0xa'


十進制轉換爲字符串

str(12)

'12'


練習:求MAC地址的下一個地址,考慮01 0f結尾的情況。

#!/usr/bin/python


macaddr = '00:16:3E:00:69:0D'

prefix = macaddr[:-2]

last_two = macaddr[-2:]

last_two_int = int(last_two,16)

new_last_two_int = last_two_int + 1

new_last_two = hex(new_last_two_int)


if len(new_last_two) == 3:

    new_last_two = '0' + new_last_two[-1:]

else:

    new_last_two = new_last_two[-2:]


newmacaddr = prefix + new_last_two

print newmacaddr.upper()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章