我写了一些我希望移植到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
Run Code Online (Sandbox Code Playgroud)
同样,如果我有:
int* j = (int*)malloc(sizeof(int));
char* c = (char*)j;
*j = 0x78FF00AA;
c is now {0xAA, 0x00, 0xFF, 0x78}
Run Code Online (Sandbox Code Playgroud)
我想在python中做类似的事情,我意识到我可以使用位操作来完成这个:
chararray=[]
num=1234567890
size=8
while len(chararray) < size:
char = chr( (num & 255 ) )
num = num >> 8
chararray.append(char)
Run Code Online (Sandbox Code Playgroud)
但是我希望有更快的方法来实现这一目标.
python有没有类似于C的联合?
您可以使用struct模块:
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']
Run Code Online (Sandbox Code Playgroud)
阅读文档页面以查找有关数据类型的内容,并注意字节顺序.