Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中转换c编写的代码_Python_C_Bittorrent - Fatal编程技术网

如何在Python中转换c编写的代码

如何在Python中转换c编写的代码,python,c,bittorrent,Python,C,Bittorrent,有人能解释一下这段代码中到底发生了什么,这样我就可以用python来写了。 我需要遵循完全相同的c编写规范,因此本部分稍后将在用于Bep33位torrent DHT的python bloom过滤器中实现 //fixed parameters k = 2 m = 256*8 //the filter byte[m/8] bloom ## function insertIP(byte[] ip) { byte[20] hash = sha1(ip) int index1 = h

有人能解释一下这段代码中到底发生了什么,这样我就可以用python来写了。 我需要遵循完全相同的c编写规范,因此本部分稍后将在用于Bep33位torrent DHT的python bloom过滤器中实现

//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})
//固定参数
k=2
m=256*8
//过滤器
字节[m/8]bloom#
函数插入(字节[]ip){
字节[20]散列=sha1(ip)

int index1=hash[0]| hash[1]sha1接受Python 2.x中的普通字符串。您可能需要直接从socket.inet_aton(ip)中获取单个字节(不确定顺序是否适合您的算法)

至于位移位,我认为Python具有相同的语法,但是如果对执行顺序有疑问,可能需要添加括号

此外,C char可以充当int,但在Python中,您需要始终使用ord()和chr()函数在它们之间显式转换


甚至像
%=
=
这样的东西也可以在Python中使用。

C和JavaScript标记在那里做什么?@alexn可能原始代码是C,而不是C,请参见例如数组类型语法(尽管它也不是真正的C)即使原始代码是c#,c等,也没关系,问题是理解逻辑,正如我提到的DHT。
 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] #>converting stringt to int
         index = [0, 1]
         hbyte = hashlib.sha1(intip) # # #sha1 doesnt accept int ? what needs to be done?
         index[0] = ord(hbyte[0])| ord(hbyte[1])<< 8 
         index[1] = ord(hbyte[2])| ord(hbyte[3])<< 8
         # how do i shift the bits?