Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Convert int to HEX

Tags:

php

hex

pack

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;
}
like image 855
wandam Avatar asked Dec 15 '22 00:12

wandam


2 Answers

You could do it with dechex in PHP:

<?php
echo dechex(10) . "\n";
echo dechex(47);
?>
like image 114
Nambi Avatar answered Feb 22 '23 07:02

Nambi


Here is a hint:

str_pad(dechex($number), 4, "0", STR_PAD_LEFT)
like image 20
Stefan Pintilie Avatar answered Feb 22 '23 07:02

Stefan Pintilie