Profesor08
Profesor08

Reputation: 1258

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.

Upvotes: 7

Views: 11964

Answers (1)

mario
mario

Reputation: 145482

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.)

Upvotes: 11

Related Questions