How to convert binary to octal number system without base functions?

Hello everyone! Here is my task to translate from binary midrange to octal. For example, 1001 = 11 in decimal. Here I found the standard function convert_basic(), but, unfortunately, the standard function cannot be used in the task. Who will help, I will be very grateful. I know how to do the process on a piece of paper, but I don’t know how to capture 3 characters.


Answer 1, authority 100%

Your questionwill not be considered a repetition. 1001(8) is 513(10).

function myoctdec($oct) {
  $n = 1;
  $dec = 0;
  $oct = (string)$oct;
  for ($i = strlen($oct)-1; $i >= 0; $i--) {
    $dec = $dec + ( (int)$oct{$i} * $n );
    $n = $n * 8;
    }
  return $dec;
  }

Reworked my answer from there. We could do it ourselves, by the way.

I’ll add it here. Works correctly with systems 2-10, but may not be the best solution in terms of performance. UPD after skype, + support up to base 32

function myconvert($num, $from = 10, $to = 10) {
  $sym = array( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V' );
  $val = array_flip($sym);
  $n = 1;
  $result = '';
  $f = strtoupper((string)$num);
  for ($i = strlen($f)-1; $i >= 0; $i--) {
    $result = $result + ( $val[$f{$i}] * $n );
    $n = $n * $from;
    }
  if ($to == 10) return $result;
  $result2 = '';
  while ($result > 0) {
    $result2 = $sym[($result % $to)].$result2;
    $result = floor($result / $to);
    }
  return $result2;
  }
echo myconvert(1001, 2, 8); // 11

Answer 2

Answer to the question in the title:

printf("binary=%b octal=%o", $n=0b1001, $n);

Result:

binary=1001 octal=11

Unless, of course, the original number is a string.