Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active July 31, 2024 09:14
Show Gist options
  • Save miguelmota/8f235b9dfd1ff1dda1d63c1df77a861e to your computer and use it in GitHub Desktop.
Save miguelmota/8f235b9dfd1ff1dda1d63c1df77a861e to your computer and use it in GitHub Desktop.
PHP byte array to hex, hex to byte array, string to hex, hex to string utility functions
<?php
function string2ByteArray($string) {
return unpack('C*', $string);
}
function byteArray2String($byteArray) {
$chars = array_map("chr", $byteArray);
return join($chars);
}
function byteArray2Hex($byteArray) {
$chars = array_map("chr", $byteArray);
$bin = join($chars);
return bin2hex($bin);
}
function hex2ByteArray($hexString) {
$string = hex2bin($hexString);
return unpack('C*', $string);
}
function string2Hex($string) {
return bin2hex($string);
}
function hex2String($hexString) {
return hex2bin($hexString);
}
?>
<?php
include('./util.php');
$byteArray = unpack('C*', 'hello');
assert(string2ByteArray('hello') == $byteArray);
assert(byteArray2String($byteArray) == 'hello');
assert(byteArray2Hex($byteArray) == '68656c6c6f');
assert(hex2ByteArray('68656c6c6f') == $byteArray);
assert(string2Hex('hello') == '68656c6c6f');
assert(hex2String('68656c6c6f') == 'hello');
?>
@JonathanBenitez10
Copy link

Like <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment