Robson » Little Red Book » Decimal to binary

Chapter 3 - Question 7

Design a program to take a positive integer and output its binary equivalent.

Solution 1

This is very simple to do in PHP.

<?    // generate a random number    $number = mt_rand(1, 100);    // output in decimal    echo $number . ' in binary is ' . decbin($number); ?>

Which produces:

35 in binary is 100011

Solution 2

Since I've learnt absolutely nothing from that, I've written a new one using a loop.

<?    // generate a random number    // this script can handles numbers much higher,    // but low numbers are used so the visitor can easily see it's correct    $number = mt_rand(1, 100);    // store the original number so it can be output later    $original = $number;      // this is going to store enough binary numbers so that    // we can work out the binary equivilant    // this could look like 1, 2, 4, 8, 16 for example    $bin_parts = array();    // add in binary numbers until there's enough    for ($n = 1; array_sum($bin_parts) <= $number; $n*=2)        // add in the number        $bin_parts[] = $n;    // reverse the array so the highest is at the start    $bin_parts = array_reverse($bin_parts);        // now loop through each number in the binary parts array    foreach ($bin_parts as $bin_part)    {        // check if the randomly generated number is equal to        // or higher than this number        if ($number >= $bin_part)        {            // if so, remove that from the number            $number -= $bin_part;            // and set this part of the output to true            $output .= 1;        }        // if not, it must be lower        else            // set this part of the output to 0            $output .= 0;    }        // show the original number and the binary equivilant    echo $original . ' in binary is ' . intval($output); ?>

Which produces:

43 in binary is 101011

Log

  • March 31, 2005 - Added solution 1 and 2.
© 2004-20 robson | cc unless stated