简体   繁体   English

PHP将大十进制数转换为十六进制

[英]PHP convert large Decimal number to Hexadecimal

I am extracting information from a certificate using php and whilst the data is returned okay, there is one particular value "SerialNumber" which is being returned in what seems to be a different number format not sure what it is.. 我正在使用php从证书中提取信息,虽然返回的数据还可以,但是有一个特定的值“ SerialNumber”以似乎是不同数字格式的形式返回,不确定它是什么。

As an example, the actual format I am expecting to receive is: 例如,我期望收到的实际格式为:

‎58 ce a5 e3 63 51 b9 1f 49 e4 7a 20 ce ff 25 0f 58 ce a5 e3 63 51 b9 1f 49 e4 7a 20 ce ff 25 0f

However, what I am actually getting back is this: 但是,我实际上得到的是:

118045041395046077749311747456482878735 118045041395046077749311747456482878735

Here is my php to perform the lookup: 这是我的PHP执行查询:

$serial = $cert['tbsCertificate']['serialNumber'];

I have tried doing a few different conversions but none of them came back with the expected format. 我尝试进行一些不同的转换,但没有一个以预期的格式返回。

Sample of a typical certificate serialnumber field.. 典型的证书序列号字段的样本。

在此处输入图片说明

VAR DUMP VAR DUMP

    ["version"]=>
    string(2) "v3"
    ["serialNumber"]=>
    object(Math_BigInteger)#5 (6) {
      ["value"]=>
      string(39) "118045041395046077749311747456482878735"
      ["is_negative"]=>
      bool(false)
      ["generator"]=>
      string(7) "mt_rand"
      ["precision"]=>
      int(-1)
      ["bitmask"]=>
      bool(false)
      ["hex"]=>
      NULL

Your SerialNumber is a Math_BigInteger object as the var_dump shows. 正如var_dump所示,您的SerialNumber是Math_BigInteger对象。 Use the toHex method to retrieve the contained number in a hexadecimal format. 使用toHex方法以十六进制格式检索包含的数字。 See reference on PEAR website . 请参阅PEAR网站上的参考。

$serial = $cert['tbsCertificate']['serialNumber'];
$valueInHex = $serial->toHex();

Note: 118045041395046077749311747456482878735 in decimal format equals to 58CEA5E36351B91F49E47A20CEFF250F in hexadecimal format. :118045041395046077749311747456482878735以十进制格式等于58CEA5E36351B91F49E47A20CEFF250F十六进制格式。 You may easily check that with an online converter like this . 您可以轻松地检查与像一个在线转换器

Here is alternative solution to convert decimal number to hexadecimal format without using external libraries. 这是在不使用外部库的情况下将十进制数转换为十六进制格式的替代解决方案。

$dec = '118045041395046077749311747456482878735';
// init hex array
$hex = array();

while ($dec) {
    // get modulus // based on docs both params are string
    $modulus = bcmod($dec, '16');
    // convert to hex and prepend to array
    array_unshift($hex, dechex($modulus));
    // update decimal number
    $dec = bcdiv(bcsub($dec, $modulus), 16);
}

// array elements to string
echo implode('', $hex);

And the output of the code ... Online Demo 以及代码的输出... 在线演示

58cea5e36351b91f49e47a20ceff250f 58cea5e36351b91f49e47a20ceff250f

You can also use string concatenation instead of array prepend. 您也可以使用字符串连接代替数组前缀。 Hope this helps. 希望这可以帮助。 Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM