我已经编写了一些我希望移植到python的C代码,因为我觉得python是一种更好的“概念”语言。
在我的C代码中,我使用内存重新解释来实现我的目标,例如:
sizeof(int) is 4 byte
sizeof(char) is 1 byte
char c[4]={0x01,0x30,0x00,0x80};
int* i=(int*)c;
*i has the value 0x80003001
同样如果我有:
int* j = (int*)malloc(sizeof(int));
char* c = (char*)j;
*j = 0x78FF00AA;
c is now {0xAA, 0x00, 0xFF, 0x78}
我想在python中做类似的事情,我意识到我可以使用位操作来实现这个目的:
chararray=[]
num=1234567890
size=8
while len(chararray) < size:
char = chr( (num & 255 ) )
num = num >> 8
chararray.append(char)
但是我希望有更快的方法来实现这一目标。
python是否有类似C的联合?
答案 0 :(得分:9)
您可以使用struct module:
import struct
# Pack a Python long as if it was a C unsigned integer, little endian
bytes = struct.pack("<I", 0x78FF00AA)
print [hex(ord(byte)) for byte in bytes]
['0xaa', '0x0', '0xff', '0x78']
阅读文档页面以查找数据类型,并注意字节顺序。