Title: struct.pack('d'... problem
Type: behavior Stage:
Components: Versions: Python 2.6
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: SchorschMCMLX, mark.dickinson
Priority: normal Keywords:

Created on 2011-09-02 23:07 by SchorschMCMLX, last changed 2011-09-03 09:18 by SchorschMCMLX. This issue is now closed.

File name Uploaded Description Edit
python-error.txt SchorschMCMLX, 2011-09-02 23:07 IDLE log demonstrating the Python output
Messages (5)
msg143443 - (view) Author: Dr. Georg Ströhlein (SchorschMCMLX) Date: 2011-09-02 23:07
Hi all,

I think there is a long-standing bug (it has made it into books on Google...) in the struct.pack() function, at least if the 'd' format string is selected. On both Win and Ubuntu the string returned for pack('!d',1.2345) is '?\xf3\xc0\x83\x12n\x97\x8d', whereas the correct 8 (!!) bytes are 3F F3 C0 83 12 6E 97 8D.

Link to a published VBA UDF for Excel is in the file; that UDF reproduces the examples given in wikipedia on the IEEE 754 / DP pages correctly. 

Regards, Schorsch
msg143444 - (view) Author: Dr. Georg Ströhlein (SchorschMCMLX) Date: 2011-09-02 23:15
link is here:
msg143454 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2011-09-03 07:22
I agree with you on the correct 8 output bytes.  And those expected bytes are exactly what struct.pack is producing here:

Python 2.7.2 |EPD 7.1-1 (32-bit)| (default, Jul  3 2011, 15:40:35) 
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "packages", "demo" or "enthought" for more information.
>>> import struct
>>> struct.pack('!d', 1.2345)
>>> len(struct.pack('!d', 1.2345))
>>> struct.pack('!d', 1.2345).encode('hex')

I suspect that the confusion arises from the way the output string is displayed:  the 8 bytes in the output string are escaped if they're not printable ASCII characters, and are displayed directly otherwise (notice the '?' and the 'n', with codes 0x3f and 0x63 respectively).
msg143456 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2011-09-03 07:26
> with codes 0x3f and 0x63 respectively

Whoops:  that should be '... 0x3f and 0x6e ...'.
msg143458 - (view) Author: Dr. Georg Ströhlein (SchorschMCMLX) Date: 2011-09-03 09:18
Thank you, Mark, for explaining the details of how to "correctly" format the output of that command to me... Regards, Schorsch
Date User Action Args
2011-09-03 09:18:26SchorschMCMLXsetmessages: + msg143458
2011-09-03 07:26:16mark.dickinsonsetmessages: + msg143456
2011-09-03 07:22:45mark.dickinsonsetstatus: open -> closed

nosy: + mark.dickinson
messages: + msg143454

resolution: not a bug
2011-09-02 23:15:20SchorschMCMLXsetmessages: + msg143444
2011-09-02 23:07:32SchorschMCMLXcreate