2016-09-28 43 views
1

我有一個8字節的十六進制代碼,我試圖通過00-FF爲每個字節從最後一個循環開始到第一個,但我是新來的python和我卡住了。在python中循環遍歷一個8字節的十六進制代碼

這裏是通過00-FF循環代碼:

for h in range(0, 256): 
    return "{:02x}".format(h) 

本質上我有什麼是

hexcode = 'f20bdba6ff29eed7' 

編輯:我要添加這個有點背景信息和刪除我以前的解釋。我正在用DES寫一個Padding Attack aglorithm。下面是需要做的:

hexcode = 'f20bdba6ff29eed7' 
for i in range(0,8): 
    (FOR i = 0) Loop through 00-FF for the last byte (i.e. 'd7') until you find the value that works 
    (FOR i = 1) Loop through 00-FF for the 7th byte (i.e. 'ee') until you find the value that works 
    and so on until the 1st byte 

我的問題:我的問題是,我不知道如何通過所有8個字節的進制的循環。當它是第8個字節時,這很容易,因爲我只是刪除最後兩個元素並通過00-FF循環並將其添加回十六進制以查看其是否正確的代碼。基本上就是代碼的功能是:

remove last two elements of hex 
try 00 as the last two elements 
if the test returns true then stop 
if it doesn't move to 01 (cont. through FF, but stop when you find the correct value) 

我的問題是,當它在中間(2-7)我如何循環的中間值,然後添加字節它全部重新走到一起。從本質上講

For byte 7: 
Remove elements 13,14 from hex 
try 00 as element 13,14 
add hex[0:12] + 00 + hex [15:16] 
if 00 returns true then stop, if not then loop through 01-ff until it does 

等爲字節6,5,4,3,2,1

+0

您的意思是使用yield而不是'return'嗎? – FatalError

+1

我不明白你在做什麼。如果你已經有'd7',爲什麼你需要通過00-ff循環呢?除了循環之外,循環*做了什麼? (你的「循環」不會因爲'return'而迭代,這實際上可能是你的全部問題......) – zwol

+0

(另外,你真的需要處理十六進制字符串*向後*嗎?如果是這樣,爲什麼?) – zwol

回答

0

這裏有一個快速的方法將字符串分解成塊。我們假設它甚至有長度。

hexcode = 'f20bdba6ff29eed7' 
l = len(hexcode) 
for n in range(0, len(hexcode)/2): 
    index = n * 2 
    print hexcode[index:index+2] 

如果您需要在字符串表示操作,你可以很容易產生用一些類似的兩個字符的字節碼的列表。就我個人而言,我更喜歡對字節進行操作,並僅將IO編碼用於十六進制編碼。

[hexcode[n*2:n*2+2] for n in range(len(hexcode)/2)] 
相關問題