Question

I would like to convert a ASCII string to Base4 (not Base64) and then convert it back. The only way I can see how to do this is to convert the string to binary then split the bits

eg:

$str = 'help'

Binary = 01101000011001010110110001110000

Base4 = 1220121112301300

is there a direct way of doing this in PHP?

Was it helpful?

Solution

Take a look at base_convert:

<?php
    class Base4 {
        public static function to($string) {
            $base4 = '';
            for ($i = 0, $strlen = strlen($string); $i < $strlen; $i++) {
                $base4 .= base_convert(ord($string[$i]), 10, 4);
            }
            return $base4;
        }

        public static function from($base4) {
            $string = '';
            for ($i = 0, $strlen = strlen($base4); $i < $strlen; $i += 4) {
                $string .= chr(base_convert(substr($base4, $i, 4), 4, 10));
            }
            return $string;
        }
    }

    $str = 'help';

    $base4 = Base4::to( $str ); 
    var_dump($base4); //string(16) "1220121112301300"

    $str = Base4::from( $base4 );
    var_dump($str); //string(4) "help"
?>

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top