Unsigned char array to an unsigned longlong array

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Aug 13 11:28:25 CEST 2009


En Tue, 11 Aug 2009 23:22:27 -0300, Jus <jus__ at hotmail.com> escribió:

> Is there a way to have an Array of unsigned longlong (C Type: unsigned
> longlong, Minimum size if bytes: 8) ?
>
> What I want to do is to store an array of bytes in an array of longlongs.
>
> To workaround this issue, I have tried to use the double array (TypeCode
> 'd'), since the size in bytes is the same (8 for instance).

Do you want to operate on it from inside Python, or manage it in some way?  
If not, use whatever format you like, even bytes. It's just a contiguous  
memory block with a known size.

> But it gives me strange result. Please look at the example:
>
>
> import array
>
> myByteArray = array.array('B', [1,2,3,4,5,6,7,8])
> myLongArray = array.array('L', myByteArray.tostring() )
>>> myLongArray = array('L', [67305985L, 134678021L])
> myDoubleArray = array.array('d', myByteArray.tostring() )
>>> myDoubleArray = array('d', [5.447603722011605e-270])
>
> If we convert the byte array to an hex form, we will get for the long  
> array:
> [04030201, 08070605].

What do you mean "convert the byte array to an hex form"?

> If we convert this hex array to decimal, we then get the Long Array:
> [67305985, 134678021].
>
>
> Now, if we do the same exercise for the double array, the hex form will  
> look
> like: [0807060504030201].
>
> And the decimal value would be: [5.784376957523072e+17].

How did you got that?

> Where does the 5.447603722011605e-270 value comes from ?

The struct module agrees:

py> s=struct.pack('q', 0x0807060504030201)
py> struct.unpack('d', s)
(5.447603722011605e-270,)

And looking at the hex representation:

py> (5.447603722011605e-270).hex()
'0x1.7060504030201p-895'

The 1. is implied, 7060504030201 are visible (52 bits), and the exponent  
is:

py> hex(-895+1023)
'0x80'

So that value seems OK to me, at least with IEEE 754 hardware...

-- 
Gabriel Genellina




More information about the Python-list mailing list