tags:

views:

370

answers:

1

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?

+9  A: 

You can use the 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']

Read the documentation page to find about datatypes, and pay attention to endianness.

Federico Ramponi