Last active
July 31, 2024 09:14
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Like <3