debian_pkgs/test_fp.py
2024-06-17 12:19:46 +02:00

37 lines
1.1 KiB
Python

def float_to_binary(f):
# Handle special cases: positive/negative infinity and NaN
if f == float('inf') or f == float('-inf') or f != f:
return bin(int.from_bytes(f.to_bytes(8, 'big', signed=True), 'big'))
# Extract sign, exponent, and mantissa
sign = 0 if f >= 0 else 1
f = abs(f)
exponent = 0
while f >= 2.0:
f /= 2.0
exponent += 1
while f < 1.0:
f *= 2.0
exponent -= 1
# Convert mantissa and exponent to binary
mantissa = bin(int((f - 1.0) * (2 ** 52)))
exponent_bits = bin(exponent + 1023)
# Format the binary representation
binary_representation = f"{sign}{exponent_bits[2:]:>011}{mantissa[2:]:<052}"
# Return the formatted binary representation
return binary_representation
# Example usage
if __name__ == "__main__":
# Get a floating-point number from the user
float_number = float(input("Enter a floating-point number: "))
# Convert the floating-point number to binary
binary_representation = float_to_binary(float_number)
# Print the binary representation
print(f"The binary representation of {float_number} is: {binary_representation}")