本文介绍了PHP按位左移32位的问题,糟糕的结果与大量的算术运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:

第一:我试图做一个32位按位上留下的大量转移,以及由于某种原因总是返回的数字原样。例如:

First: I am trying to do a 32-spaces bitwise left shift on a large number, and for some reason the number is always returned as-is. For example:

echo(516103988<<32); // echoes 516103988

由于比特左移一个空格是乘以2的等效,我试图由2 ^ 32数相乘,和它的工作原理,它返回2216649749795176448

Because shifting the bits to the left one space is the equivalent of multiplying by 2, i tried multiplying the number by 2^32, and it works, it returns 2216649749795176448.

二:我必须从上述点增加9379到号:

Second: I have to add 9379 to the number from the above point:

printf('%0.0f', 2216649749795176448 + 9379); // prints 2216649749795185920

应该打印:2216649749795185827

Should print: 2216649749795185827

推荐答案

根据帕斯卡·马丁的建议,我想无论是BCMath和GMP延伸,并与以下解决方案提出了:

Based on Pascal MARTIN's suggestions, i tried both the BCMath and the GMP extension and came up with the following solutions:

使用BCMath:

$a = 516103988;
$s = bcpow(2, 32);
$a = bcadd(bcmul($a, $s), 9379);
echo $a; // works, echoes 2216649749795185827

通过GMP:

$a = gmp_init(516103988);
$s = gmp_pow(gmp_init(2), 32);
$a = gmp_add(gmp_mul($a, $s), gmp_init(9379));
echo gmp_strval($a);  // also works

据我了解,有一个在服务器GMP再上安装BCMath大得多的机会,所以我将使用第一个解决方案。

From what i understand, there is a far greater chance for BCMath to be installed on the server then GMP, so i will be using the first solution.

感谢:)

这篇关于PHP按位左移32位的问题,糟糕的结果与大量的算术运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:19