2017-04-12 162 views
2

我是一個初學者,所以很抱歉,如果這是顯而易見的。Python 3:ValueError:無效文字爲int()與基數10:'0001.0110010110010102e + 22'

我在這裏不知所措。我一直在試圖製作一個加密/解密程序,但我一直收到這個錯誤。我知道在這個問題上還有其他問題,但我仍然無法解決它。

加密器

import binascii 
def text_to_bits(text, encoding='utf-8', errors='surrogatepass'): 
    bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:] 
    return bits.zfill(8 * ((len(bits) + 7) // 8)) 

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'): 
    n = int(bits, 2) 
    return int2bytes(n).decode(encoding, errors) 

def int2bytes(i): 
    hex_string = '%x' % i 
    n = len(hex_string) 
    return binascii.unhexlify(hex_string.zfill(n + (n & 1))) 

#ENCRYPTION ALGORITHM 
algorithm = 61913299 

#ASCII ----> NUMBERS 
raw = input("Enter text to encrypt:") 

binary = text_to_bits(raw) 
binary = int(binary) 
algorithm = int(algorithm) 
encrypted = binary * algorithm 
encrypted = str(encrypted) 
print(encrypted) 

print("Done") 

解密:

import sys 
import time 

def to_bin(string): 
    res = '' 
    for char in string: 
     tmp = bin(ord(char))[2:] 
     tmp = '%08d' %int(tmp) 
     res += tmp 
    return res 

def to_str(string): 
    res = '' 
    for idx in range(len(string)/8): 
     tmp = chr(int(string[idx*8:(idx+1)*8], 2)) 
     res += tmp 
    return res 

incorrectpasswords = 0 
password=("password") 
originpassword = password 
x = 1 
algorithm = 61913299 

while x==1: 
    passwordattempt =input("Enter Password:") 
    if passwordattempt == password: 
     print("Correct") 
     x = 2 

    if passwordattempt!= password: 
     print("Incorrect") 
     incorrectpasswords = incorrectpasswords + 1 
    if incorrectpasswords > 2: 
     if x == 1: 
      print("Too many wrong attempts, please try again in one minute.") 
      time.sleep(60) 


encrypted = input("Enter numbers to unencrypt:") 

encrypted = int(encrypted) 

one = encrypted/algorithm 
size = sys.getsizeof(one) 
one = str(one).zfill(size + 1) 
one = int(one) 
unencrypted = to_str(one) 

x = unencrypted 

對於二進制和文本,文本和二進制之間的轉換,我使用了一些代碼,我在網上找到。

+0

不它說哪一行是錯誤? –

+0

@MatthewCiaramitaro是的,對不起。第49行。'one = int(one)' –

+1

與Python早期版本不同,Python 3中的'/'或「真除法」操作符即使在用'ints'調用時也會返回一個浮點數。如果它適合你的算法,你可以使用'//'或者「floor division」,只要它的輸入是'int'就可以返回。 –

回答

0

我相信你的代碼是不工作的原因是:

one = encrypted/algorithm 

生成浮動

把你的字符串回一個數字,你應該申請

eval(one) 

float(one) 

代替

int(one) 

(你也可以把它變成一個int將float或EVAL)之後 或者您可能能夠通過使用整數除法//得到它,而不是/,這將使one類型int通過地板的divison的十進制結果,但我不知道這是你在Python 3外殼尋找

實例的行爲:

>>> import sys 
>>> one = 15/25 
>>> size = sys.getsizeof(one) 
>>> one = str(one).zfill(size+1) 
>>> one 
'00000000000000000000000.6' 
>>> type(one) 
<class 'str'> 
>>> one = eval(one) 
>>> one 
0.6 
>>> type(one) 
<class 'float'> 
+0

當我這樣做,我得到一個錯誤:TypeError:eval()arg 1必須是一個字符串,字節或代碼對象 –

+0

你做它後,你把它變成一個字符串?或者你之前做過? –

+0

它應該被應用而不是'one = int(one)' –

相關問題