簡體   English   中英

結合for循環和while循環

[英]Combine for loop with while loop

我試圖寫一個python腳本,將找到X我的意思是

x & 0xe = 0x6

我想找到所有可以給我x & 0xe = 0x6的十六進制結果的組合

所以我做的第一件事是創建一個腳本來測試x & 0xe = 0x6以便我可以找到一些X組合

GetStr=(raw_input('1st Hex:'))
GetStr2=hex(0xe)

StrToHex=int(GetStr,16)
StrToHex2=int(GetStr2,16)
cal = (hex(StrToHex & StrToHex2))

while cal != hex(0x6):
    print "no"
    GetStr = (raw_input('1st Hex:'))
    GetStr2 = hex(0xe)

    StrToHex = int(GetStr, 16)
    StrToHex2 = int(GetStr2, 16)
    cal = (hex(StrToHex & StrToHex2))
else:
    print GetStr

第二個腳本是for循環,它將創建將在while循環中測試的所有組合

GetStr=(raw_input('1st Hex:'))
StrToHex = int(GetStr, 16)

GetStr2=hex(0x100)
StrToHex2=int(GetStr2,16)

for i in range(StrToHex,StrToHex2,1):
    print hex(i)

事情是我發現很難使其以我想要的方式工作,它所要做的就是找到所有可能合計為0x6組合並打印出來。

謝謝!

首先,請注意,不可能找到x所有值,使得x & 0xe == 0x6 ,因為它們無限多。 bin(0x6)'0b110'bin(0xe)'0b1110' ,因此每個數字都具有相同位數的位,而其他所有位數均不為0xe將是一個解決方案。

關於您的代碼:不清楚您要問什么。 據我了解的問題,您想將手動方法從第一個代碼段轉換為一個循環,以自動測試特定范圍內的所有數字。 為此,我建議創建一個可在兩個循環中重用的check函數,並為其他兩個值定義一些變量。 另外,當前您正在不斷地從int轉換為hex -string並返回到int 一直使用int並轉換為hex進行打印。

您可以嘗試如下操作:

# function used in both loops
def check(first, second, target):
    return first & second == target

# manual loop with user input
second, target = 0xe, 0x6
print("find solution for x & 0x%x = 0x%x" % (second, target))
while True:
    first = int(raw_input('1st hex: '), 16)
    if check(first, second, target):
        print("yes")
        break
    else:
        print("no")

甚至更短(但可能不那么可讀):

while not check(int(raw_input('1st hex: '), 16), second, target):
    print("no")
print("yes")

然后,只需在for循環中調用該函數即可。

# automated loop testing values in range
upper = 0x100
for n in range(upper):
    if check(n, second, target):
        print(hex(n))

暫無
暫無

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

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