php字符串为十六进制with2的补码: [英] php string to hex with2's complement:

查看:92
本文介绍了php字符串为十六进制with2的补码:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串193390663,我想用2's compliment将该字符串转换为hex.输出为0B86E847

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

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

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]));
    }
}

更新1

尝试过

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

输出

b86e847

但是我想要类似0B86E847

任何帮助将不胜感激.

推荐答案

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

Solution you are looking for is as below,

它是从给出的答案之一中引用的. PHP中带符号的int的表示形式.

<?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);

这篇关于php字符串为十六进制with2的补码:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆