Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,023 questions

51,974 answers

573 users

How to convert a number to any base in PHP

1 Answer

0 votes
function toBase(int $n, int $base): string
{
    $digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    if ($base < 2 || $base > 36) {
        throw new InvalidArgumentException("Base must be between 2 and 36");
    }

    if ($n === 0) {
        return "0";
    }

    $result = "";

    while ($n > 0) {
        $remainder = $n % $base;
        $result .= $digits[$remainder];
        $n = intdiv($n, $base);
    }

    return strrev($result);
}

try {
    $number = 255;

    echo $number . " in base 2  = " . toBase($number, 2) . PHP_EOL;
    echo $number . " in base 8  = " . toBase($number, 8) . PHP_EOL;
    echo $number . " in base 16 = " . toBase($number, 16) . PHP_EOL;
    echo $number . " in base 36 = " . toBase($number, 36) . PHP_EOL;

} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . PHP_EOL;
}



/*
run:

255 in base 2  = 11111111
255 in base 8  = 377
255 in base 16 = FF
255 in base 36 = 73

*/

 



answered 5 hours ago by avibootz
...