note 83173 added to function.base-convert

From: Date: Wed, 14 May 2008 05:42:31 +0000
Subject: note 83173 added to function.base-convert
Groups: php.notes 
Request: Send a blank email to php-notes+get-139365@lists.php.net to get a copy of this message
Spent almost a day to find a bug(?) in base_convert() function when converting big values to binary: <?php $value = 2919739656537; echo base_convert($value, 10, 2); ?> should print 101010011111001110000010111000100101011001 in reality, prints 10101000111000001100011100110101110110100100 but that is wrong! so, in result, I've written this two functions: <?php /** * Convert binary to decimal * works with big numbers * * @param string $binary * @return float */ function big_bin2dec($binary) { $result = (float)0; $shift = 0; while ( 0 < strlen($binary) ) { $bit = substr($binary, -1); $binary = substr($binary, 0, -1); $result = $result + $bit*pow(2, $shift); ++$shift; } return $result; } /** * convert decimal 2 binary presentation * * @param mixed $dec * @return string */ function big_dec2bin($dec) { $result = ''; $shift = 0; while ( pow(2, $shift) < $dec ) { ++$shift; } while ( 0 <= $shift ) { $pow = pow(2, $shift); if ( $pow <= $dec ) { $dec-= $pow; $result = $result . '1'; } else { $result = $result . '0'; } --$shift; } return $result; } ?> Functions tested only with positive integers(that's enough for me), so if you need more than this you'll, possibly, have to rework 'em. Simple test: <?php $value = pow(2, 48);//only one bit should be set printf("%f \n", $value); echo base_convert($value, 10, 2), "\n"; echo big_dec2bin($value), "\n"; ?> prints out something similar to: 281474976710656.000000 110011001100110011001100110011001100111001010 1000000000000000000000000000000000000000000000000 I hope this will help someone :) BTW! My phpinfo() says PHP Version 5.2.1 ---- Server IP: 195.54.192.44 Probable Submitter: 127.0.0.1 (proxied: 80.68.253.62) ---- Manual Page -- http://www.php.net/manual/en/function.base-convert.php Edit -- https://master.php.net/note/edit/83173 Del: integrated -- https://master.php.net/note/delete/83173/integrated Del: useless -- https://master.php.net/note/delete/83173/useless Del: bad code -- https://master.php.net/note/delete/83173/bad+code Del: spam -- https://master.php.net/note/delete/83173/spam Del: non-english -- https://master.php.net/note/delete/83173/non-english Del: in docs -- https://master.php.net/note/delete/83173/in+docs Del: other reasons-- https://master.php.net/note/delete/83173 Reject -- https://master.php.net/note/reject/83173 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#139365) next »