I'm trying to convert a string of ASCII characters to their octal equivalent and can't for the life of me figure it out. Any one know?
1 Answer
I'd just use ord and base_convert. Use ord to get the ascii value in decimal, then base_convert to make it octal.
$oct = base_convert(ord($char), 10, 8);
Here's what you seek in the form of a function:
function string_to_octal($str)
{
$chars = str_split($str);
$rtn = "";
foreach ($chars as $c) { $rtn .= str_pad(base_convert(ord($c), 10, 8), 3, 0, STR_PAD_LEFT); }
return $rtn;
}
Note: str_pad is included because the result won't always be a 3-byte chunk.
Example of the above code in action.
edit: As @brbcoding pointed out, you can use decoct($c) in place of base_convert($c, 10, 8).
3 Comments
brbcoding
Could you use
decoct() instead of base_convert() in this situation?Mr. Llama
@brbcoding Absolutely. I wasn't aware there was a
decoct function, so I fell back to the ultra-generic base_convert function.brbcoding
Cool... I haven't really ever run into this issue, but was trying to figure it out too. Here's that line w/
decoct... foreach ($chars as $c) { $rtn .= decoct(ord($c)); }