What if you divide 7 by 32 in binary?
$7\div32=0.21875$Double the fractional part of the number one after another and write the result below.
1>>> $0.21875\times2=0.4375$, integral part is 0 and fractional part is 0.4375.
2>>> $0.4375\times2=0.875$, integral part is 0 and fractional part is 0.875.
3>>> $0.4375\times2=1.75$, integral part is 1 and fractional part is 0.75.
4>>> $0.75\times2=1.5$, integral part is 1 and fractional part is 0.5.
5>>> $0.5\times2=1.0$, integral part is 1 and fractional part is 0.
The binary number you want is the integer parts from the top.
So equivalent binary of fractional is 0.00111. When the denominator is a power of 2, it is easier to convert. $$ \begin{aligned} \dfrac{7}{32}&=\dfrac{4}{32}+\dfrac{2}{32}+\dfrac{1}{32}\\ &=\dfrac{1}{8}+\dfrac{1}{16}+\dfrac{1}{32}\\ &=\dfrac{1}{2^3}+\dfrac{1}{2^4}+\dfrac{1}{2^5}\\ &=0.00111\ (2) \end{aligned} $$ So equivalent binary of fractional is 0.00111.
Or 7 is 111 in binary, and 32 is $2^5$.
Shift the binary number 111 to the right by 5 bits, it gives 0.00111.
def DecToBin(number, precition=10, base=2):
integerPart = int(number)
fractionalPart = number - integerPart
binary = ''
# Convert integer part to binary
while integerPart:
binary = str(integerPart%base) + binary
integerPart = integerPart//base
# Convert fraction part to binary
binary += '.'
while fractionalPart and precition:
fractionalPart *= base
integerPart = int(fractionalPart)
fractionalPart = fractionalPart - integerPart
binary += str(integerPart)
precition -= 1
return binary
number = 7/32
print(DecToBin(number))
>>> .00111
Comments
Post a Comment