簡體   English   中英

有沒有更短的方法來增加 python 中的 bd_address ?

[英]Is there a shorter way to increment bd_address in python?

我寫了一個 python 的函數來將 BT 設備 BD_ADDR 增加任何值,但我的函數最多只能工作到 xx:xx:xx:xx:FE:FF。 例如,原始 BD_ADDR = AA:BB:CC:DD:EE:FF --> 增加 1 BD_ADDR = AA:BB:CC:DD:EF:00。 在沒有所有 if 語句的情況下,是否還有更短的方法可以做到這一點? 任何建議將不勝感激。 下面是腳本:

def ba_incr(mac,incr):
        old_bytes = mac[12:].split(":")
        if (old_bytes[0] != "00"):
             if (old_bytes[0] != "01" and old_bytes[0] != "0F"):
                  old_hex = str(old_bytes[0] + old_bytes[1])
                  incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                  new_bytes = str(incr_hex[:2]) + ":" + str(incr_hex[2:])
             elif (old_bytes[0] == "0F" and old_bytes[1] == "FF") :
                  old_hex = str(old_bytes[0] + old_bytes[1])
                  incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]

                  new_bytes = str(incr_hex[:2]) + ":" + str(incr_hex[2:])
                else:
                        old_hex = str(old_bytes[0] + old_bytes[1])
                        incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                        #print ("incremented hex",incr_hex)
                        new_bytes = "0" + str(incr_hex[:1]) + ":" + str(incr_hex[1:])
        elif (old_bytes[0] == "00" and old_bytes[1] == "FF"):
                old_hex = old_bytes[1]
                #print ("old hex:",old_hex)
                incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                #print ("incremented hex:",incr_hex)
                new_bytes = "01" + ":" + str(incr_hex[1:])
        elif (old_bytes[0] == "00" and old_bytes[1][:1] == "0") and old_bytes[1][1:] != "F":
                old_hex = old_bytes[1]
                #print ("old hex:",old_hex)
                incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                #print ("incremented hex:",incr_hex)
                new_bytes = old_bytes[0] + ":0" + str(incr_hex)
        elif (old_bytes[0] == "00" and old_bytes[1] != "FF"):
                old_hex = old_bytes[1]
                #print ("old hex:",old_hex)
                incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                #print ("incremented hex:",incr_hex)
                new_bytes = old_bytes[0] + ":" + str(incr_hex)[:2]
        print ("mac after:", mac[:12] + new_bytes.upper())

你可能可以嘗試這樣的事情:

  1. 從mac地址中刪除“:”
  2. 將mac地址轉換為整數
  3. 增加整數值
  4. 將整數轉換為十六進制字符串
  5. 在適當的位置重新插入“:”

對我有用的示例代碼(為簡單起見,我增加了 1)。 您可能需要修改它以處理極端情況。

s = 'AA:BB:CC:DD:EE:FF'
s = s.replace(':', '')
val = int(s, 16)
val = val + 1
incr_s = hex(val)
incr_s = incr_s[2:].upper()
incr_s = ':'.join(incr_s[i:i+2] for i in range(0, len(incr_s), 2))
print(s)
print(incr_s)

輸出:

AABBCCDDEEFF
AA:BB:CC:DD:EF:00

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM