Integer (representing a sequence of bits) reinterpretation as Character Array in Python

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:


while len(chararray) < size:
   char = chr( (num & 255 ) )
   num = num >> 8

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:

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.

Need Your Help

Azure Website 301 Redirect - Where Do I Put It? iis redirect azure web-config

I want to direct some of my other domains to my primary domain which is hosted at a Windows Azure website.

Remove one image from array per click

jquery html arrays append

I want to remove one image from the array every time someone clicks the remove button. I tried using the splice method but I couldn't get it to work because the image still appear to be visible aft...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.