Octal numbers have digits that are all in the range [0,7]
. Thus, 58
and 59
are not octal numbers, and your method should be expected to give erroneous results.
The reason that 58
evaluates to 101000
is because the first digit of the octal number expands to the first three digits of the binary number. 5 = 101_2
. Same story for the second part, but 8 = 1000_2
, so you only get the 000
part.
An alternate explanation is that 8 = 0 (mod 8)
(I am using the =
sign for congruency here), so both 8
and 0
will evaluate to 000
in binary using your code.
The best solution would be to do some input validation. For example, while converting you could check to make sure the digit is in the range [0,7]