PHP 的 base_convert 问题, 应该如何处理?

2018-09-02 15:53:41 +08:00
 eecjimmy
$dec = '200000000000000000000000';
$hex = '2a5a058fc295ec000000';
echo '$dec = ' . $dec . "\n";
echo '$hex = ' . $hex . "\n";
echo 'strcmp(base_convert($dec,10,16), $hex) === 0 : ' . var_export(strcmp(base_convert($dec, 10, 16), $hex) === 0, true) . "\n";
echo 'strcmp(base_convert($hex,16,10), $hex) === 0 : ' . var_export(strcmp(base_convert($hex, 16, 10), $hex) === 0, true) . "\n";

执行结果如下:

$dec = 200000000000000000000000
$hex = 2a5a058fc295ec000000
strcmp(base_convert($dec,10,16), $hex) === 0 : true
strcmp(base_convert($hex,16,10), $hex) === 0 : false

手册上面是写了这样的警告, 如果数据大的话, 会出现精度丢失.

2059 次点击
所在节点    PHP
5 条回复
eecjimmy
2018-09-02 16:01:32 +08:00
但是需要把大数字转换为 16 进制, 应当如何处理呢?
nullen
2018-09-02 16:04:50 +08:00
feiyuanqiu
2018-09-02 16:25:45 +08:00
jhdxr
2018-09-02 17:16:26 +08:00
http://php.net/manual/zh/function.base-convert.php#51077

function gmp_convert($num, $base_a, $base_b)
{
return gmp_strval ( gmp_init($num, $base_a), $base_b );
}
eecjimmy
2018-09-03 11:13:43 +08:00
@nullen gmp 好像没相应的方法.
@jhdxr @feiyuanqiu 谢谢, 已经解决了.
我把链接里面的代码贴出来了.
```php
// Input: A decimal number as a String.
// Output: The equivalent hexadecimal number as a String.
function dec2hex($number)
{
$hexvalues = array('0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F');
$hexval = '';
while($number != '0')
{
$hexval = $hexvalues[bcmod($number,'16')].$hexval;
$number = bcdiv($number,'16',0);
}
return $hexval;
}

// Input: A hexadecimal number as a String.
// Output: The equivalent decimal number as a String.
function hex2dec($number)
{
$decvalues = array('0' => '0', '1' => '1', '2' => '2',
'3' => '3', '4' => '4', '5' => '5',
'6' => '6', '7' => '7', '8' => '8',
'9' => '9', 'A' => '10', 'B' => '11',
'C' => '12', 'D' => '13', 'E' => '14',
'F' => '15');
$decval = '0';
$number = strrev($number);
for($i = 0; $i < strlen($number); $i++)
{
$decval = bcadd(bcmul(bcpow('16',$i,0),$decvalues[$number{$i}]), $decval);
}
return $decval;
}
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/485379

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX