data conversion question (binary string to 'real string')

Bengt Richter bokr at oz.net
Fri Jul 25 17:57:39 CEST 2003


On Fri, 25 Jul 2003 14:57:57 +0200, Alexander Eisenhuth <stacom at stacom-software.de> wrote:

>Hallo all there,
>
>maby I don't see the forest because of all that trees, but :
>
>from struct import *
>
>
># how can I convert
>f = float(0.5)
>
># with
>bin_str =  pack('!f', 0.5)
>
># now bin_str is '?\x00\x00\x00'
>
>
># to "3F000000" ?????
>
>
That leading '?' is the character representation of a string byte whose ordinal value
is 3F hex, followed by three characters represented by \x00 (whose ordinal
values are zero). I.e., your binary bytes are being represented as characters in a string,
and when it's shown interactively you see the values as a sequence of character glyphs
(or \x.. hex escape representations if no glyphs are available), which is the normal way
to display a string.

If you want the *hex string* representation of that string-represented byte sequence, you can
convert each byte-as-character first to its ordinal value and then the ordinal value to a
2-char hex string representation, and then join those all into a single string,
e.g.,, showing the character transformations:

 >>> [c for c in struct.pack('!f', 0.5)]
 ['?', '\x00', '\x00', '\x00']
 >>> [ord(c) for c in struct.pack('!f', 0.5)]
 [63, 0, 0, 0]
 >>> ['%02X'%ord(c) for c in struct.pack('!f', 0.5)]
 ['3F', '00', '00', '00']

And finally, all you need is

 >>> ''.join(['%02X'%ord(c) for c in struct.pack('!f', 0.5)])
 '3F000000'

Now you have a hex string representation of the network-ordered (big-endian-ordered)
bytes of a single precision (32-bit) float.

Regards,
Bengt Richter




More information about the Python-list mailing list