Monday, 10 June 2013

How to convert decimal number to octal number

The octal numeral system, or oct for short, is the base-8 number system, and uses the digits 0 to 7. Octal widely used in computing when systems such as the PDP-8, ICL 1900 and IBM mainframes employed 12-bit, 24-bit or 36-bit words.

Steps to convert a decimal number to octal number:

1. Take modulas(%) of decimal number by 8.
2. Now divide decimal number by 8.
3. Repeat these steps until condition matches.
4. Now reverse that number.

Go through the code given below.

<?php
     $numberToConvert = 78;
     if($numberToConvert > 0){
           $tempArray = array();
           echo "Octal of $numberToConvert is : ";
           while($numberToConvert){
               $tempArray[] = $numberToConvert%8;
               $numberToConvert = (int)($numberToConvert/8);
           }
           for($i = count($tempArray); $i >=0; $i--){
               echo $tempArray[$i];
           }      
     }else{
           echo 'Number should be greater then zero.';
     }
?>
Output is : Octal of 78 is : 116

1 comment: