1

Hi I have problem with parsing -0.000000e+00 on linux( on windows is working).

struct.pack( "d", -0.000000e+00 )

On linux struct.pack change -0.000000e+00 to 0.000000e+00. When i print value before pack is correct but result of struct.pack is like it was 0.000000e+00.

Is there any solution to solve this problem.

I think i need to add negative number witch is closest to 0. How to do that?

EDIT struct.pack( "d", -0.000000e+00 ) result '\x00\x00\x00\x00\x00\x00\x00\x80'

struct.pack( "!d", -0.000000e+00 )result '\x00\x00\x00\x00\x00\x00\x00\x00'

struct.pack( "<d", -0.000000e+00 )result '\x00\x00\x00\x00\x00\x00\x00\x00'

struct.pack( ">d", -0.000000e+00 )result '\x00\x00\x00\x00\x00\x00\x00\x00' I want to use "< d" and " > d".

EDIT Sry not error.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Luffy
  • 677
  • 1
  • 6
  • 19
  • Please post [the code you're using](http://sscce.org/). For this question, the CPU architecture may also be relevant. `struct.unpack('d', struct.pack( "d", -0.000000e+00 ))[0]` works fine on Linux/amd64 with cpython 3.2 and 2.7. – phihag Jul 31 '12 at 08:36

1 Answers1

1

The struct format string "d" encodes the value in a platform-specific way. Most likely, the platform you decode the bytestring on has a different endianess or length of doubles. Use the ! format character to force a platform-independent encoding:

>>> struct.pack('!d', -0.)
b'\x80\x00\x00\x00\x00\x00\x00\x00' # IEEE754 binary64 Big Endian
>>> struct.unpack('!d', b'\x80\x00\x00\x00\x00\x00\x00\x00')[0]
-0.0

Also make sure that you use a supported Python version. In cPython<2.5, struct is known to be buggy. Update to a current version, like 2.7 or 3.2.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • Its not working for me :( Return \x00\x00\x00\x00\x00\x00\x00\x00 – Luffy Jul 31 '12 at 08:47
  • @Luffy Are you absolutely certain that you have used the above code? Can you paste a part of a terminal session to [pastebin](http://pastebin.com) or so? And what architecture, Linux distribution, and Python version are you running your tests on? Also make sure that you use `'!d'` to decode as well, and not only to encode. – phihag Jul 31 '12 at 08:49
  • Python 2.4.3 I dont knew atm what is architecture. But not common. – Luffy Jul 31 '12 at 08:54
  • Fortunately, that's enough information. cPython 2.4's struct (and not only that) is indeed broken. You should switch to a Python implementation from this decade. – phihag Jul 31 '12 at 09:04