php字符串为十六进制,带有2的补码:

问题描述 投票:1回答:1

嗨,我有一个字符串193390663,我想用hex转换为2's compliment。输出为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的输出

任何帮助将不胜感激。

php string hex
1个回答
1
投票

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

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);
© www.soinside.com 2019 - 2024. All rights reserved.