$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
手册上面是写了这样的警告, 如果数据大的话, 会出现精度丢失.
已经处理了. 代码贴出来
// 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;
}
1
eecjimmy OP 但是需要把大数字转换为 16 进制, 应当如何处理呢?
|
3
feiyuanqiu 2018-09-02 16:25:45 +08:00 1
|
4
jhdxr 2018-09-02 17:16:26 +08:00 1
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 ); } |
5
eecjimmy OP @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; } ``` |