Conversion from binary to octal in python

Python program for Conversion from binary to octal. Here more solutions.

``````#  Python 3 program for
#  Convert Binary number into Octal number
class Convert :
# Convert decimal number into octal
def  octal(self, number) :
result = 0
multiplier = 1
remainder = 0
while (number != 0) :
remainder = number % 8
result = (remainder * multiplier) + result
multiplier *= 10
number = int(number / 8)
return result
def binaryToOctal(self, num) :
if (len(num) == 0) :
# When empty binary number
return
# Some useful variable
flag = False
decimalNo = 0
counter = 0
index = len(num) - 1
# We Assume that given binary number is valid
# Here - indicates negative binary number
# First convert binary to decimal
# Example = 10111 => 23
while (index >= 0) :
if (num[index] == '1') :
decimalNo += (1 << counter)
elif(num[index] != '0') :
if (index == 0 and num[index] == '-') :
# When get negative number
flag = True
else :
# Not a valid binary number
return
counter += 1
index -= 1
# When given number is
output = self.octal(decimalNo)
if (flag == True) :
output = -output
# Display given number
print("Binary :",num," Octal :",output)

if __name__=="__main__":
# Test Case

Output

``````Binary : 1111  Octal : 17
Binary : 10111  Octal : 27
Binary : 101011  Octal : 53
Binary : 11011  Octal : 33
Binary : -1000110  Octal : -106``````

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.