0
transform binar into octal number with Python3
Wassup. I would like to create the code for transform binar number into octal ( 10-2-8 ). And i get it. But IT work ONLY while in "for"-"if" cycles be 1 instead z[i]... I think, u already understood what I would like do) Help me pls) Code: https://code.sololearn.com/c1FY8YMPDx3G/#py
2 odpowiedzi
+ 5
Lil Shi you should use int(hH) in the if condition rather than just hH as it's a string. But anyway, it gives you wrong answer 'cause that's not how we convert binary to octal.
All you are doing is:
Suppose I entred: 2
2 in binary system : 10, fine
Now you're trying to convert 10 to octal the same way we'd convert 10 to decimal i.e. Multiply each subsequent digit with increasing power of 2. But that's not how it's work.
There are ways to convert binary to octal directly. You can read about them.
What I prefer to do is convert binary to decimal by multiplying powers of 2 and then decimal to octal by just taking remainders by 8.
+ 3
You can transform a string, that has binary shape, into int directly by using int(thatstring, 2).
You can then turn it into an octal representation by oct.
You can also do it with input and output.
The code:
print(oct(int(input(), 2)))