Igal name
Igal name

Reputation: 9

getting unexpected result when using Python's struct.pack method

When i'm using python's struct.pack method i'm getting a weird result. The code looks like this:

>>> struct.pack('<i', 0x01d1f23a)

The result i'm trying to get is the hex address converted to little endian ("<"). EDITED: Equivalent to Perl (sorry for the print's, don't know perl)

#!/usr/bin/perl
my $eip = pack('V',0x01ccf23a); 
print "$eip[0]";
print "$eip[1]";
print "$eip[2]";
print "$eip[3]";

the result is: 582422041

I need to achieve the same result with python.

Upvotes: 0

Views: 648

Answers (1)

u354356007
u354356007

Reputation: 3225

Everything seems to be fine:

>>> struct.pack('<i', 0x01d1f23a)
b':\xf2\xd1\x01'

Most significant byte 01 is stored at the highest memory address, thus giving little endian. The only thing I may notice is that b'\x3a' looks like : because it is a valid ASCII symbol.

If the answer doesn't addresses your issue, please update your post with details.

Edit

In order to have the number represented as a sequence of bytes in hex form, without conversion to ASCII, use the following line:

>>> ' '.join(hex(b) for b in struct.pack('<i', 0x01d1f23a))
'0x3a 0xf2 0xd1 0x1'

Use str instead of hex to get decimal representation.

>>> ' '.join(str(b) for b in struct.pack('<i', 0x01d1f23a))
'58 242 209 1'

Upvotes: 1

Related Questions