嗨,我有一个字符串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
的输出
任何帮助将不胜感激。
您正在寻找的解决方案如下,
从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);