代码在返回语句处卡住
我在写一个Python测试代码,用来实现SHA1算法,但遇到了一些问题,搞不清楚怎么回事。看起来代码在一个返回语句那里卡住了,但我不知道为什么会这样。
def testMakeWords():
msg = Message(0xff00ff00800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020)
msg.padded_message = 0xff00ff00800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020
word_list = msg.packageWords()
print("Returned:", word_list)
print("Expected: [ff00ff00, 80000000, 00000000, 00000000, 00000000, 00000000, 00000000, 00000000, 00000000, 00000000, 00000000, 00000000, 00000000, 00000000, 00000000, 00000020]")
class Message():
def __init__(self, message, length=None):
self.raw_input = message
self.workingValue = message
self.initialLength = self.__sanitizeLength__(length)
self.padded_message = []
self.word_list = []
self.messageBlocks = []
self.initial_hash = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]
"""takes a message, and packages it into a list of words."""
def packageWords(self):
wordSize = 32
binaryMessage = bin(self.padded_message)[2:]
wordList = []
startIndex = 0
endIndex = wordSize
for k in range(0, len(binaryMessage), wordSize):
print("Indecies: {} -- {}".format(startIndex, endIndex))
wordValue = int(binaryMessage[startIndex:endIndex], 2)
newWord = Word32(wordValue)
wordList.append(newWord)
startIndex = startIndex + wordSize
endIndex = endIndex + wordSize
self.word_list = wordList
print("blah blah blah")
return wordList
class Word32(Word):
def __init__(self, value):
self.wordSize = 32
self.value = self.__checkValue__(value)
"""internal method, checks that the value given to a word is not larger than the size of that word."""
def __checkValue__(self, value):
if len(bin(value)[2:]) > self.wordSize:
print("ERROR: word value greater than word length")
return
return value
def __repr__(self):
binString = bin(self.value)[2:]
while (len(binString) < self.wordSize / 4):
hexString = "0" + binString
binString = binString
return binString
为了简单起见,我只放了那个卡住的部分方法。运行代码时,packageWords
方法里的所有代码都会打印出来,但在调用packageWords
之后的两个打印语句却没有输出。代码显示仍在运行,但什么也没有发生。
我对这里发生的事情感到困惑。
- 我添加了一些我正在使用的单词类的代码,去掉了一些与这个问题无关的函数,比如rotate。
1 个回答
0
你在 Word32.__repr__
方法里定义了一个无限循环。这个错误和以下几行代码有关:
while (len(binString) < self.wordSize / 4):
hexString = "0" + binString
你有一个循环,它的停止条件是 binString
的长度必须大于等于 self.wordSize / 4
。但是循环体内并没有改变 binString
的长度,所以这个循环永远不会停止。
如果你把它改成:
while (len(binString) < self.wordSize / 4):
binString = "0" + binString
那么你的循环最终会停止。
一般来说,你可能需要多想想,少写代码,因为像下面这样的代码:
binString = binString
让我觉得你只是试着写一些东西,直到有一个能工作的,而不是先理解问题再想出合适的解决方案。祝你好运!