在PHP中创建带符号的int的十六进制表示 [英] Create hex-representation of signed int in PHP

查看:76
本文介绍了在PHP中创建带符号的int的十六进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析一个二进制文件,偶然发现了一些我需要将其从十六进制转换为dec,反之亦然的16bit(2字节)值.正值看起来像是"0075"(117),而负值看起来像是"FE75"(-395).

I'm parsing a binary and stumbled upon some 16bit (2 byte) values that I need to convert from hex to dec and vice versa. Positive values look like this "0075" (117) while negative ones look like that "FE75" (-395).

我正在使用此功能将十六进制转换为有符号的int,这是可行的,但我似乎找不到找到将有符号的int转换为十六进制表示的解决方案.

I'm using this function to convert from hex to signed int, which works, but I can't seem to find a solution for signed int to hex-representation.

function hexdecs($hex)
{
    // ignore non hex characters
    $hex = preg_replace('/[^0-9A-Fa-f]/', '', $hex);

    // converted decimal value:
    $dec = hexdec($hex);

    // maximum decimal value based on length of hex + 1:
    //   number of bits in hex number is 8 bits for each 2 hex -> max = 2^n
    //   use 'pow(2,n)' since '1 << n' is only for integers and therefore limited to integer size.
    $max = pow(2, 4 * (strlen($hex) + (strlen($hex) % 2)));

    // complement = maximum - converted hex:
    $_dec = $max - $dec;

    // if dec value is larger than its complement we have a negative value (first bit is set)
    return $dec > $_dec ? -$_dec : $dec;
}

推荐答案

感谢您的所有评论,我结束了,这正是我想要的.

Thanks for all your comments, I ended up with this and it's just what I wanted.

您太棒了!

/**
 * Converts signed decimal to hex (Two's complement)
 *
 * @param $value int, signed
 *
 * @param $reverseEndianness bool, if true reverses the byte order (see machine dependency)
 *
 * @return string, upper case hex value, both bytes padded left with zeros
 */
function signed2hex($value, $reverseEndianness = true)
{
    $packed = pack('s', $value);
    $hex='';
    for ($i=0; $i < 2; $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;
}

这篇关于在PHP中创建带符号的int的十六进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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