<p>Ok, so PHP isn't the best language to be dealing with arbitrarily large integers in, considering that it only natively supports 32-bit signed integers. What I'm trying to do though is create a class that could represent an arbitrarily large binary number and be able to perform simple arithmetic operations on two of them (add/subtract/multiply/divide).</p>

<p>My target is dealing with 128-bit integers.</p>

<p>There's a couple of approaches I'm looking at, and problems I see with them. Any input or commentary on what you would choose and how you might go about it would be greatly appreciated.</p>

<p><strong>Approach #1:</strong> Create a 128-bit integer class that stores its integer internally as four 32-bit integers. The only problem with this approach is that I'm not sure how to go about handling overflow/underflow issues when manipulating individual chunks of the two operands.</p>

<p><strong>Approach #2:</strong> Use the bcmath extension, as this looks like something it was designed to tackle. My only worry in taking this approach is the scale setting of the bcmath extension, because there can't be any rounding errors in my 128-bit integers; they must be precise. I'm also worried about being able to eventually convert the result of the bcmath functions into a binary string (which I'll later need to shove into some mcrypt encryption functions).</p>

<p><strong>Approach #3:</strong> Store the numbers as binary strings (probably LSB first). Theoretically I should be able to store integers of any arbitrary size this way. All I would have to do is write the four basic arithmetic functions to perform add/sub/mult/div on two binary strings and produce a binary string result. This is exactly the format I need to hand over to mcrypt as well, so that's an added plus. This is the approach I think has the most promise at the moment, but the one sticking point I've got is that PHP doesn't offer me any way to manipulate the individual bits (that I know of). I believe I'd have to break it up into byte-sized chunks (no pun intended), at which point my questions about handling overflow/underflow from Approach #1 apply.</p>

[{'answer_id': 37422, 'author': 'SCdF', 'author_id': 1666, 'author_profile': 'https://Stackoverflow.com/users/1666', 'pm_score': 2, 'selected': False, 'text': '<p>There are already various <a href="http://www.pear.php.net/package/Crypt_DiffieHellman/docs/latest/Crypt_DiffieHellman/BigInteger/Crypt_DiffieHellman_Math_BigInteger_Interface.html" rel="nofollow noreferrer">classes</a> <a href="http://pear.php.net/package/Math_BigInteger/docs/latest/Math_BigInteger/_Math_BigInteger-1.0.0RC3---BigInteger.php.html" rel="nofollow noreferrer">available</a> for this so you may wish to look at them before writing your own solution (if indeed writing your own solution is still needed).</p>\n'}, {'answer_id': 37434, 'author': 'watchwood', 'author_id': 2227, 'author_profile': 'https://Stackoverflow.com/users/2227', 'pm_score': 1, 'selected': False, 'text': "<p>As far as I can tell, the bcmath extension is the one you'll want.  The data in the PHP manual is a little sparse, but you out to be able to set the precision to be exactly what you need by using the bcscale() function, or the optional third parameter in most of the other bcmath functions.  Not too sure on the binary strings thing, but a bit of googling tells me you ought to be able to do with by making use of the pack() function.</p>\n"}, {'answer_id': 1381855, 'author': 'Jonathon Hill', 'author_id': 168815, 'author_profile': 'https://Stackoverflow.com/users/168815', 'pm_score': 3, 'selected': True, 'text': '<p>The <a href="http://us2.php.net/gmp" rel="nofollow noreferrer">PHP GMP extension</a> will be better for this. As an added bonus, you can use it to do your decimal-to-binary conversion, like so:</p>\n\n<pre><code>gmp_strval(gmp_init($n, 10), 2);\n</code></pre>\n'}, {'answer_id': 20730795, 'author': 'Alix Axel', 'author_id': 89771, 'author_profile': 'https://Stackoverflow.com/users/89771', 'pm_score': 0, 'selected': False, 'text': '<p>I implemented the following <a href="https://github.com/alixaxel/phunction/blob/ac2bc87e0d6d6c944a46d9714ca79004b18319c0/phunction/Math.php#L74-L143" rel="nofollow">PEMDAS complaint BC evaluator</a> which may be useful to you.</p>\n\n<pre><code>function BC($string, $precision = 32)\n{\n    if (extension_loaded(\'bcmath\') === true)\n    {\n        if (is_array($string) === true)\n        {\n            if ((count($string = array_slice($string, 1)) == 3) &amp;&amp; (bcscale($precision) === true))\n            {\n                $callback = array(\'^\' =&gt; \'pow\', \'*\' =&gt; \'mul\', \'/\' =&gt; \'div\', \'%\' =&gt; \'mod\', \'+\' =&gt; \'add\', \'-\' =&gt; \'sub\');\n\n                if (array_key_exists($operator = current(array_splice($string, 1, 1)), $callback) === true)\n                {\n                    $x = 1;\n                    $result = @call_user_func_array(\'bc\' . $callback[$operator], $string);\n\n                    if ((strcmp(\'^\', $operator) === 0) &amp;&amp; (($i = fmod(array_pop($string), 1)) &gt; 0))\n                    {\n                        $y = BC(sprintf(\'((%1$s * %2$s ^ (1 - %3$s)) / %3$s) - (%2$s / %3$s) + %2$s\', $string = array_shift($string), $x, $i = pow($i, -1)));\n\n                        do\n                        {\n                            $x = $y;\n                            $y = BC(sprintf(\'((%1$s * %2$s ^ (1 - %3$s)) / %3$s) - (%2$s / %3$s) + %2$s\', $string, $x, $i));\n                        }\n\n                        while (BC(sprintf(\'%s &gt; %s\', $x, $y)));\n                    }\n\n                    if (strpos($result = bcmul($x, $result), \'.\') !== false)\n                    {\n                        $result = rtrim(rtrim($result, \'0\'), \'.\');\n\n                        if (preg_match(sprintf(\'~[.][9]{%u}$~\', $precision), $result) &gt; 0)\n                        {\n                            $result = bcadd($result, (strncmp(\'-\', $result, 1) === 0) ? -1 : 1, 0);\n                        }\n\n                        else if (preg_match(sprintf(\'~[.][0]{%u}[1]$~\', $precision - 1), $result) &gt; 0)\n                        {\n                            $result = bcmul($result, 1, 0);\n                        }\n                    }\n\n                    return $result;\n                }\n\n                return intval(version_compare(call_user_func_array(\'bccomp\', $string), 0, $operator));\n            }\n\n            $string = array_shift($string);\n        }\n\n        $string = str_replace(\' \', \'\', str_ireplace(\'e\', \' * 10 ^ \', $string));\n\n        while (preg_match(\'~[(]([^()]++)[)]~\', $string) &gt; 0)\n        {\n            $string = preg_replace_callback(\'~[(]([^()]++)[)]~\', __FUNCTION__, $string);\n        }\n\n        foreach (array(\'\\^\', \'[\\*/%]\', \'[\\+-]\', \'[&lt;&gt;]=?|={1,2}\') as $operator)\n        {\n            while (preg_match(sprintf(\'~(?&lt;![0-9])(%1$s)(%2$s)(%1$s)~\', \'[+-]?(?:[0-9]++(?:[.][0-9]*+)?|[.][0-9]++)\', $operator), $string) &gt; 0)\n            {\n                $string = preg_replace_callback(sprintf(\'~(?&lt;![0-9])(%1$s)(%2$s)(%1$s)~\', \'[+-]?(?:[0-9]++(?:[.][0-9]*+)?|[.][0-9]++)\', $operator), __FUNCTION__, $string, 1);\n            }\n        }\n    }\n\n    return (preg_match(\'~^[+-]?[0-9]++(?:[.][0-9]++)?$~\', $string) &gt; 0) ? $string : false;\n}\n</code></pre>\n\n<p>It automatically deals with rounding errors, just set the precision to whatever digits you need.</p>\n'}]
['https://Stackoverflow.com/questions/37391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1384/']