Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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:

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?

like image 660
Mike Hamer Avatar asked Jan 24 '23 23:01

Mike Hamer


1 Answers

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.

like image 195
Federico A. Ramponi Avatar answered Feb 06 '23 15:02

Federico A. Ramponi