MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / bin_to_octal

Function bin_to_octal

conversions/binary_to_octal.py:21–39  ·  view source on GitHub ↗
(bin_string: str)

Source from the content-addressed store, hash-verified

19
20
21def bin_to_octal(bin_string: str) -> str:
22 if not all(char in "01" for char in bin_string):
23 raise ValueError("Non-binary value was passed to the function")
24 if not bin_string:
25 raise ValueError("Empty string was passed to the function")
26 oct_string = ""
27 while len(bin_string) % 3 != 0:
28 bin_string = "0" + bin_string
29 bin_string_in_3_list = [
30 bin_string[index : index + 3]
31 for index in range(len(bin_string))
32 if index % 3 == 0
33 ]
34 for bin_group in bin_string_in_3_list:
35 oct_val = 0
36 for index, val in enumerate(bin_group):
37 oct_val += int(2 ** (2 - index) * int(val))
38 oct_string += str(oct_val)
39 return oct_string
40
41
42if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected