2012-01-27 117 views
1

如何在hashlib.sha1(int)中取整數。 請參閱對此我以IP爲字符串轉換它作爲整數現在hash.sha1利己整數取代碼...python sha1取整數

import hashlib 
import socket 
import struct 
    class blommy(object): 
    def __init__(self): 
    self.bitarray= [0]*2048 

    def hashes(self,ip): 
    #convert decimal dotted quad string to long integer" 
    intip= struct.unpack('>L',socket.inet_aton(ip))[0] 
    index = [0, 1] 
    hbyte = hashlib.sha1(intip) # how to take sha1 of integer?? 
    index[0] = ord(hbyte[0])| ord(hbyte[1])<< 8 
    index[1] = ord(hbyte[2])| ord(hbyte[3])<< 8 

需要將此C代碼轉換爲蟒蛇。請建議上面編寫代碼的一部分。如果我把IP作爲int我不能計算sha1 +,即使使用套接字轉換IP比sha1不接受它的建議?看到下面的評論

//fixed parameters 
k = 2 

m = 256*8 

    //the filter 
    byte[m/8] bloom ## 

function insertIP(byte[] ip) { 

byte[20] hash = sha1(ip) 

int index1 = hash[0] | hash[1] << 8 # how to in python? 
int index2 = hash[2] | hash[3] << 8 

// truncate index to m (11 bits required) 
index1 %= m ## ? 
index2 %= m ## ? 

// set bits at index1 and index2 
bloom[index1/8] |= 0x01 << index1 % 8 ## ?? 
bloom[index2/8] |= 0x01 << index2 % 8 ## ?? 
} 

// insert IP 192.168.1.1 into the filter: 
    insertIP(byte[4] {192,168,1,1}) 
+2

除了八位字節序列以外,沒有任何其他概念可以用作sha1摘要;你真的想做什麼? – SingleNegationElimination 2012-01-27 21:07:34

+0

這就是我想要做的,你可以看到這個C代碼?參數 //過濾器 k = 2 m = 256 * 8 //過濾器 byte [m/8] bloom ##這部分是什麼? 函數insertIP(byte [] ip){ byte [20] hash = sha1(ip) int index1 = hash [0] | hash [1] << 8 int index2 = hash [2] | hash [3] << 8 //截斷索引到m(需要11位) index1%= m ##? index2%= m ##? //在index1和index2設置位 bloom [index1/8] | = 0x01 << index1%8 ## ?? bloom [index2/8] | = 0x01 << index2%8 ## ?? } //將IP 192.168.1.1插入過濾器: insertIP(byte [4] {192,168,1,1}) – Shazib 2012-01-28 08:00:35

+0

請將新代碼添加到您的答案;它在評論形式中是不可取的。 – SingleNegationElimination 2012-01-28 13:38:16

回答

0

你的問題的答案是否定的,你可以計算字符串的散列,但不是整數。嘗試這樣的:

hashlib.sha1(str(1234)).digest() 

以您的整數的散列作爲一個字符串。