Tell me, please, how to implement a function that will convert numbers from a binary system to octal with a fractional part (2.5, for example)?
1 answer
The numbers in the binary system are multipliers in front of the corresponding powers of two, depending on the position. For example: 10.1 2 == 1⋅2 1 + 0⋅2 0 + 1⋅2 -1 . The numbers in the fractional part are facing negative degrees.
In the octal system, the basis is 8, that is 2 3 . Therefore, every three bits correspond to one octal digit. For example: 010 2 == 2 8 , 100 2 == 4 8 .
For convenience of converting, the fractional part can be added with zeros so that the length becomes a multiple of three: 10.1 2 == 10.100 2 == 2.4 8 . In Python 3:
from math import ceil def bin2oct_float(bits): n, dot, f = bits.partition('.') return bin2oct(n) + dot + bin2oct(f.ljust(3 * ceil(len(f) / 3), '0')) where bin2oct(bits) can "01" transform ( set("01").issuperset(bits) ):
def bin2oct(bits): return bits and '{:o}'.format(int(bits, 2)) Example:
>>> bin2oct_float('10.1') '2.4' You can not convert to int , but only on the lines of the operation to produce:
def bin2oct(bits, bits2digit={'{:03b}'.format(i): str(i) for i in range(8)}): bits = bits.zfill(3 * ceil(len(bits) / 3)) return ''.join([bits2digit[bits[i:i+3]] for i in range(0, len(bits), 3)]) The code uses the idiom of traversing a sequence of exactly n elements at a time . The code does not support characters, spaces in the input: '+1.111' , '- 1.0' .
When transferring code to a language without built-in dictionaries, you can use analogs of nested lists in order to select an octal digit by three bits:
def bits2digit(a, b, c): return [['01','23'], ['45','67']][a][b][c] Example:
>>> bits2digit(1, 0, 0) '4'