简体   繁体   English

将C ++指针代码转换为python

[英]Convert c++ pointer code to python

I have a code snippet in C++ which needs to converted to Python: 我在C ++中有一个代码段,需要转换为Python:

static void DecryptBuff (const unit8_t key, char* buf, const size_t n) {
   for (auto ptr = buf; ptr < buf +n; ++ptr)
      *ptr = *ptr ^ key;
}

The value being sent to the "DecryptBuff" is address of some variable. 发送到“ DecryptBuff”的值是某个变量的地址。 The data type of the variable can be anything and so the "for" is not easy to use. 变量的数据类型可以是任何东西,因此“ for”不易于使用。

I know that python does not have pointers, is there any other way I can approach this problem? 我知道python没有指针,还有其他方法可以解决这个问题吗?

You are using your pointer basically as an array. 您基本上将指针用作数组。 You can use array.array , which works in a similar way to C arrays. 您可以使用array.array ,其工作方式与C数组类似。

You could write this using a Python list for the C char *buf , mutating the list so that it contains the result, but a more Pythonic way is to create a new buffer containing the xor-encoded bytes and return it. 您可以使用C char *buf的Python list来编写此代码,对list进行变异,使其包含结果,但更Python化的方式是创建一个包含异或编码字节的新缓冲区并返回它。

With older versions of Python you'd create a list of the ord() values of each char in the buf string, xor the elements of that list with your key, convert the ints back to chars using chr() , and then join() the individual chars back into a single string. 使用旧版本的Python时,您需要在buf字符串中创建每个char的ord()值列表,然后用键对列表中的元素进行异或chr() ,然后使用chr()将int转换回chars,然后进行join()将单个字符重新组合成一个字符串。 But with more modern versions of Python you can get bytearray to do most of the dirty work. 但是,使用更现代的Python版本,您可以获得字节数组来完成大多数工作。

#! /usr/bin/env python

def xor_crypt(key, buf):
    return str(bytearray([i ^ key for i in bytearray(buf)]))

plaintxt = "Hello, world!"
key = 42

print 'original ', `plaintxt`

encrypted = xor_crypt(key, plaintxt)
print 'encrypted', `encrypted`

decrypted = xor_crypt(key, encrypted)
print 'decrypted', `decrypted`

output 产量

original  'Hello, world!'
encrypted 'bOFFE\x06\n]EXFN\x0b'
decrypted 'Hello, world!'

But if you really want to imitate the C code more closely and mutate buf , you can easily do that, like this: 但是,如果您真的想更紧密地模仿C代码并更改buf ,则可以轻松地做到这一点,如下所示:

#! /usr/bin/env python

def xor_crypt(key, buf):
    buf[:] = bytearray([i ^ key for i in buf])

plaintxt = "Hello, world!"
key = 42

buf = bytearray(plaintxt)
print 'original ', `buf`, str(buf)

xor_crypt(key, buf)
print 'encrypted', `buf`

xor_crypt(key, buf)
print 'decrypted', `buf`

output 产量

original  bytearray(b'Hello, world!') Hello, world!
encrypted bytearray(b'bOFFE\x06\n]EXFN\x0b')
decrypted bytearray(b'Hello, world!')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM