16/03/2012

Problems with bindec 64bits

I have experience some problem using bindec and sprintf for 64bits binary string. The only cause that I can think of that is float number issues in php. I haven't tried any solution. But I do think bcmath may help in the case.

<?php
for($j = 0; $j < 15; $j++) {
   $binary_string = str_repeat('1', 64);
   for ($i = 0; $i < $j; $i++) {
      $binary_string[$i] = '0';
   }
   $ret = bindec($binary_string);
   $dec = sprintf("%.0f", $ret);
   echo "\n{$binary_string}\t{$ret}\t{$dec}";

   for ($i=63; $i>$j; $i--) {
      $binary_string[$i] = '0';
      $ret = bindec($binary_string);
      $dec = sprintf("%.0f", $ret);
      echo "\n{$binary_string}\t{$ret}\t{$dec}";
   }
   echo "\n";
}

This piece of code will generate some problematic outcome. If you look at some set of outcome at top of each set for first 10 sets. Although binary string are different. their bindec and sprintf outcome are different. Now we are temporary changed to use 32 bits. But is there anyone out there who can explain what has happened; The outcome is as following:


1111111111111111111111111111111111111111111111111111111111111111 1.844674407371E+19 18446744073709551616
1111111111111111111111111111111111111111111111111111111111111110 1.844674407371E+19 18446744073709551616
1111111111111111111111111111111111111111111111111111111111111100 1.844674407371E+19 18446744073709551616
1111111111111111111111111111111111111111111111111111111111111000 1.844674407371E+19 18446744073709551616
1111111111111111111111111111111111111111111111111111111111110000 1.844674407371E+19 18446744073709551616
1111111111111111111111111111111111111111111111111111111111100000 1.844674407371E+19 18446744073709551616
1111111111111111111111111111111111111111111111111111111111000000 1.844674407371E+19 18446744073709551616
1111111111111111111111111111111111111111111111111111111110000000 1.844674407371E+19 18446744073709551616
1111111111111111111111111111111111111111111111111111111100000000 1.844674407371E+19 18446744073709551616
1111111111111111111111111111111111111111111111111111111000000000 1.844674407371E+19 18446744073709551616
1111111111111111111111111111111111111111111111111111110000000000 1.844674407371E+19 18446744073709551616
1111111111111111111111111111111111111111111111111111100000000000 1.844674407371E+19 18446744073709549568
1111111111111111111111111111111111111111111111111111000000000000 1.844674407371E+19 18446744073709547520
......
Post a Comment