php 字符串以 2 的补码转十六进制:

php string to hex with2's complement:

您好,我有一个字符串 193390663,我想用 2's compliment 将其转换为 hex。输出是 0B86E847

现在我正在使用下面的函数,但它给了我 313933333930363633

 public static function String2Hex($string)
{
    $hex = '';
    for($i=0; $i<strlen($string); $i++)
    {
        $hex.=dechex(ord($string[$i]));
    }
}

更新 1

试过这个

 $sub2 = substr($m->msn,4,9);
            $m->m_hex = dechex ($sub2);

输出

b86e847

但我想要像 0B86E847

这样的输出

非常感谢任何帮助。

您正在寻找的解决方案如下,

它引用自 Create hex-representation of signed int in PHP 给出的答案之一。

<?php

function signed2hex($value, $reverseEndianness = true)
{
    $packed = pack('i', $value);
    $hex='';
    for ($i=0; $i < 4; $i++){
        $hex .= strtoupper( str_pad( dechex(ord($packed[$i])) , 2, '0', STR_PAD_LEFT) );
    }
    $tmp = str_split($hex, 2);
    $out = implode('', ($reverseEndianness ? array_reverse($tmp) : $tmp));
    return $out;
}

echo signed2hex(193390663);