PHP Convert int to HEX

和自甴很熟 提交于 2020-01-13 20:28:05

问题


How can I get a similar function with pack/unpack (or other short function)?

function getHEX($number) {
    switch($number) {
        case 0: $ret = "\x00\x00\x00\x00"; break;
        case 1: $ret = "\x00\x00\x00\x01"; break;
        case 2: $ret = "\x00\x00\x00\x02"; break;
        case 3: $ret = "\x00\x00\x00\x03"; break;
        // (...)

        default: $ret = "\x00\x00\x00\x00";
    }

    return $ret;
}

回答1:


You could do it with dechex in PHP:

<?php
echo dechex(10) . "\n";
echo dechex(47);
?>



回答2:


This function has solved my problem

pack("H*", sprintf("%08X", $number));



回答3:


Here is a hint:

str_pad(dechex($number), 4, "0", STR_PAD_LEFT)


来源:https://stackoverflow.com/questions/22373293/php-convert-int-to-hex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!