-
Notifications
You must be signed in to change notification settings - Fork 70
3. Binary Representation of Floating Point Numbers
Bora Canbula edited this page Nov 25, 2023
·
1 revision
To convert a floating point number into binary representation, splitting the number into integer and fractional parts should be the first step.
x = 13.375
We can get the integer part easily as follows:
integer_part = int(x)
Extracting the fractional part can be tricky for newbies:
fractional_part = x - int(x)
You can convert an integer into binary following the steps:
- Divide the integer by 2
- Get the remainder
- Repeat until the quotient is 0
- Reverse the order of the remainders
def convert_integer_to_binary(n):
if n == 0:
return "0"
s = ""
while n > 0:
s += str(n % 2)
n //= 2
return s[::-1]
You can convert an integer into binary following the steps:
- Multiply the fraction by 2
- Get the integer part of the result
- Continue with the fractional part of the result
- Repeat while the fractional part is not 0
- Use the integers in the order they were obtained
def convert_fractional_to_binary(n):
if n == 0:
return "0"
s = ""
while n > 0:
n *= 2
s += str(int(n))
n -= int(n)
return s
Once you have the both integer and fractional parts, you can concentrate two parts and truncate or pad the result with zeros to get the desired precision.
x = 13.375
integer_part = int(x)
fractional_part = x - int(x)
binary_number = (
convert_integer_to_binary(integer_part)
+ "."
+ convert_fractional_to_binary(fractional_part)
)
Keep in mind that these steps can be applied to conversion from decimal to any base. It doesn't have to be base-2, so called binary.