Skip to content

Instantly share code, notes, and snippets.

@fisknils
Created August 19, 2015 17:58
Show Gist options
  • Save fisknils/6011db33174b862b6787 to your computer and use it in GitHub Desktop.
Save fisknils/6011db33174b862b6787 to your computer and use it in GitHub Desktop.
for converting each character in a string to a string of hex values
<?PHP
// returns the hex value of a single character (if a string is supplied, only the first character will be processed)
function charhex($c) {
return dechex(ord($c[0]));
}
// returns the hex values of each character in string with optional delimiter
function stringhex($s,$delimiter="") {
$ret = "";
for($i=0;$i<strlen($s);$i++) {
$ret .= charhex($s[$i]).$delimiter;
}
return (strlen($delimiter) ? substr($ret,0,-strlen($delimiter)) : $ret);
}
/*
example code:
echo stringhex("hello world")."\n";
echo stringhex("hello world",":")."\n";
echo stringhex("hello world","::")."\n";
echo stringhex("hello world","\n")."\n";
output:
68656c6c6f20776f726c64
68:65:6c:6c:6f:20:77:6f:72:6c:64
68::65::6c::6c::6f::20::77::6f::72::6c::64
68
65
6c
6c
6f
20
77
6f
72
6c
64
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment