繁体   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