0

Hi I have a string 193390663 which I want to convert into the hex with 2's compliment. The output is 0B86E847

Right now I am using below function but it's giving me 313933333930363633

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

Update 1

Tried this

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

Output

b86e847

But I want output like 0B86E847

Any help would be highly appreciated.

1
  • @NigelRen So what is the correct way of getting hex with 2's compliment ? Commented May 22, 2020 at 12:26

1 Answer 1

1

Solution you are looking for is as below,

It is referenced from one of the answer given at 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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.