faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 14 people (36%) answered Yes
Recently 3 of 10 people (30%) answered Yes

Entry

Converting data to little endian

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 346, Fredrik Lundh


"""
Packages: maths.bit_twiddling
"""
"""
> > Hi, I was wondering how to get my data to be represented in little
> > endian format.  I know that I can use the socket functions to convert to
> > network byte order (big endian), but I need to convert to little endian
> > (not just the host byte order).
> 
> One possibility is to use the NumPy extensions and store your data in a
> multiarray object.  There is a byteswapped method of the multiarray object
> that lets you byteswap your data.
footnote: the standard array module also provides
a byteswap operation:
"""
import array
a = array.array("i", [1, 2])
print a
# array('i', [1, 2])
a.byteswap()
print a
# array('i', [16777216, 33554432])
"""
> There is also a way to check the endianness of your machine (so
> you can determine whether or not to byteswap).
from array-example-4.py in the eff-bot guide:
"""
def little_endian():
    return ord(array.array("i",[1]).tostring()[0])