Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array of bytes to a hex string?

I have a solution, but this solution is slow. Example:

$arr = array(14, 0, 1, 0, 0, 0, 0, 0, 0, 224, 0, 255, 255, 255, 255, 255);
$hex_str = "";
foreach ($arr as $byte)
{
    $hex_str .= sprintf("%02X", $byte);
}

Result is: 0E0001000000000000E000FFFFFFFFFF

Format is:

255 => FF
0 => 00
1 => 01
14 => 0E

If you know a faster solution, share it please.

like image 906
Profesor08 Avatar asked Feb 09 '23 16:02

Profesor08


1 Answers

You could cast each integer to an char first.

$chars = array_map("chr", $arr);

Then make it a string:

$bin = join($chars);

And finally convert that to a hex string:

$hex = bin2hex($bin);

See: array_map, chr, join, bin2hex. (And of course you could do it all in one line.)

like image 149
mario Avatar answered Feb 12 '23 11:02

mario