/**
* Group Memebers -
* Arnav Jain, Xiao Qi Lee
* Lab #2
* Write a program using any language that converts a floating point
* number to the simple model of the floating point representation
*
*/
import java.util.Scanner;
public class FloatingPointConverter {
public static String floatToSimpleModel(float num) {
// Handle special cases: positive/negative zero and
positive/negative infinity
if (num == 0) {
return "00000000000000"; // 1 bit for sign, 5 bits for
exponent, 8 bits for significand
} else if (num == Float.NEGATIVE_INFINITY) {
return "10000000000000"; // Negative infinity
} else if (num == Float.POSITIVE_INFINITY) {
return "01000000000000"; // Positive infinity
}
// Handle negative numbers
String signBit = "0";
if (num < 0) {
signBit = "1";
num = -num;
}
// Convert the floating-point number to binary
StringBuilder binary = new StringBuilder();
float fraction = num - (int) num;
int integerPart = (int) num;
// Convert integer part to binary
while (integerPart > 0) {
binary.insert(0, integerPart % 2);
integerPart /= 2;
}
// Add decimal point
binary.append('.');
// Convert fractional part to binary
while (fraction != 0) {
fraction *= 2;
if (fraction >= 1) {
binary.append('1');
fraction -= 1;
} else {
binary.append('0');
}
}
// Separate the integer and fractional parts
String[] parts = binary.toString().split("\\.");
// Calculate exponent and adjust the decimal point
int exponent = parts[0].length() - 1 + 15;
String intPart = parts[0].substring(1); // Remove the leading 1
String fracPart = String.format("%-8s", parts[1]).replace(' ',
'0'); // Pad with zeros if necessary
// Ensure exponent is within range
if (exponent >= 31) {
exponent = 31;
intPart = "11111"; // Set all exponent bits to 1 to represent
infinity
}
// Format the result
return signBit + String.format("%5s",
Integer.toBinaryString(exponent))
.replace(' ', '0') + intPart + fracPart.substring(0, 8);
}
//The main function takes user input and calls the floatToSimpleModel
//function to convert the input number into its IEEE 754
representation. It then prints the result.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a floating point number: ");
float num = scanner.nextFloat();
System.out.println("Simple model representation: " +
floatToSimpleModel(num));
scanner.close();
}
}
Output: