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

2024-10-02 18:21:58 发布

您现在位置: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;
}

发送到“DecryptBuff”的值是某个变量的地址。变量的数据类型可以是任何类型,因此“for”不容易使用。你知道吗

我知道python没有指针,有没有其他方法可以解决这个问题?你知道吗


Tags: key代码forautosize地址static数据类型
2条回答

您使用的指针基本上是一个数组。可以使用^{},其工作方式与C数组类似。你知道吗

您可以使用Python list为C char *buf编写此代码,对列表进行变异,使其包含结果,但更为Python的方法是创建一个包含xor编码字节的新缓冲区并返回它。你知道吗

对于较早版本的Python,您可以创建buf字符串中每个字符的ord()值的列表,将该列表的元素与键异或,使用chr()将int转换回字符,然后join()将单个字符转换回单个字符串。但是有了更现代的Python版本,你可以让bytearray来做大部分的脏活。你知道吗

#! /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`

输出

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

但是,如果您真的想更紧密地模仿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`

输出

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

相关问题 更多 >