I’ve written some C code that I would like to port to python, as I feel python is a better ‘concept’ language.
In my C code, I use memory reinterpretation to achieve my goals, for example:
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
similarly if i have:
int* j = (int*)malloc(sizeof(int)); char* c = (char*)j; *j = 0x78FF00AA; c is now {0xAA, 0x00, 0xFF, 0x78}
I would like to do a similar thing in python, I realise that I can use bit operations to accomplish this:
chararray=[] num=1234567890 size=8 while len(chararray) < size: char = chr( (num & 255 ) ) num = num >> 8 chararray.append(char)
However I was hoping there would be a faster way of accomplishing this.
Does python have anything similar to C’s union?
You can use the struct module:
Read the documentation page to find about datatypes, and pay attention to endianness.