0

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 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Could you use decoct() instead of base_convert() in this situation?
@brbcoding Absolutely. I wasn't aware there was a decoct function, so I fell back to the ultra-generic base_convert function.
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)); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.