long integer - 64-bit Float Literals PHP -


i'm trying convert 64-bit float 64-bit integer (and back) in php. need preserve bytes, i'm using pack , unpack functions. functionality i'm looking java's double.doubletolongbits() method. http://docs.oracle.com/javase/7/docs/api/java/lang/double.html#doubletolongbits(double)

i managed far comments on php docs pack():

function encode($int) {         $int = round($int);          $left = 0xffffffff00000000;         $right = 0x00000000ffffffff;          $l = ($int & $left) >>32;         $r = $int & $right;          return unpack('d', pack('nn', $l, $r))[1]; } function decode($float) {         $set = unpack('n2', pack('d', $float));         return $set[1] << 32 | $set[2]; } 

and works well, part...

echo decode(encode(10000000000000)); 

100000000

echo encode(10000000000000); 

1.1710299640683e-305

but here's gets tricky...

echo decode(1.1710299640683e-305); 

-6629571225977708544

i have no idea what's wrong here. try yourself: http://pastebin.com/zwkc97z7

you'll need 64-bit php on linux. site seems emulate setup: http://www.compileonline.com/execute_php_online.php

it working properly, problem in case in logic of:

echo decode(1.1710299640683e-305); 

you can't use "rounded" , "human readable" output of echo function decode original value (because loosing precision of double then).

if save return of encode(10000000000000) variable , try decode again works (you can use echo on 10000000000000 without loosing precision).

please see example below can execute on http://www.compileonline.com/execute_php_online.php well:

<?php     function encode($int) {         $int = round($int);          $left = 0xffffffff00000000;         $right = 0x00000000ffffffff;          $l = ($int & $left) >>32;         $r = $int & $right;          return unpack('d', pack('nn', $l, $r))[1];     }      function decode($float) {         $set = unpack('n2', pack('d', $float));         return $set[1] << 32 | $set[2];     }      echo decode(encode(10000000000000)); // untouched     echo '<br /><br />';      $encoded = encode(10000000000000);     echo $encoded; // loosing precision!      echo ' - "human readable" version of encoded int<br /><br />';      echo decode($encoded); // still works - happy days! ?> 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -