Byte-Array to String

Steven Howe howe.steven at gmail.com
Thu Apr 19 11:51:16 EDT 2007


Robert Rawlins - Think Blue wrote:
> Hello Guys,
>
>  
>
> I have a byte array passed to me by dbus and I'm looking to convert it into
> a string? Is that possible? Sorry for seeming like a putts with these
> questions, I'm not used to all these complex data types :-D
>
>  
>
> The byte array looks something like this when printed to screen.
>
>  
>
> dbus.Array([dbus.Byte(54), dbus.Byte(0), dbus.Byte(24), dbus.Byte(9),
> dbus.Byte(0), dbus.Byte(0), dbus.Byte(10), dbus.Byte(0), dbu
> s.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(9), dbus.Byte(0),
> dbus.Byte(1), dbus.Byte(53), dbus.Byte(3), dbus.Byte(25), dbus.
> Byte(16), dbus.Byte(0), dbus.Byte(9), dbus.Byte(2), dbus.Byte(0),
> dbus.Byte(53), dbus.Byte(3), dbus.Byte(9), dbus.Byte(1), dbus.By
> te(1)], signature=dbus.Signature('y'))
>
>  
>
> Thanks again,
>
>  
>
> Rob
> *
> *
When reading about array, I wondered what the hell it was good for. Now 
I see. It's a tool to build objects
to pass to the Operating System or other applications. Something like 
ctypes. The OS might store data from left to right, or right to left, or 
not use IEEE standards (which VMS certainly doesn't). So the data you 
give/get from the system call must be massaged by the application before 
it's usable.

python/lib/module-array.html (5.14 array -- Efficient arrays of numeric 
values)
*array.tostring*( )
/Convert the array to an array of machine values and return the string 
representation (the same sequence of bytes that would be written to a 
file by the tofile() method.)/

I wonder if this is the method you are looking for.
So you have an object dbus.Array, which, obviously is from a call to the 
dbus (another application's data) that contains 28 byte arrays. I would 
assume you know which you want, say the first one.

    myDbusString01 = dbus.Array[0].tostring()

or to get the lot:

    myDbusStrings = []  #create a new empty list
    for array in dbus.Array:
        myDbusStrings.append( array.tostring() )

At this point you should have the array converted. But you will still 
need a reference as to what you have. The call to the dbus should have 
some documentation abut what it's returning.
Also I'd expect the second example to be very bad programming, as some 
of the array elements are probably not going to be characters. They 
could be integers, floats or booleans. So creating a dictionary to 
handle specific array element handling is probably a better, less error 
prone, method of attack.

Not have the contents and defination of your dbus.array handy, I can't 
test this, but the approach seems reasonable.

Steven Howe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070419/f8b19070/attachment.html>


More information about the Python-list mailing list