1.浮点格式示例
2.上代码
public class Main {
static StringBuilder endValue;
public static void main(String[] args) {
String data = "B8D1B717";
//String data = "42987C32";
//String data = "461C4000";
endValue = new StringBuilder();
StringBuffer buffer = new StringBuffer();
char[] chars = data.toCharArray();
for (int i = 0; i < data.length(); i++) {
buffer.append(hexToBin(chars[i]));
}
System.out.println(buffer);
getIEEEFloatValue(buffer);
}
public static void getIEEEFloatValue(StringBuffer buffer) {
if (buffer.substring(0, 1).equals("0")) {
//为正
} else {
//为负
endValue.append("-");
}
String E = buffer.substring(1, 9);
String M = buffer.substring(9, buffer.length());
Integer EDec = Integer.parseInt(E, 2);
System.out.println("E:" + EDec);
Integer MDec = Integer.parseInt(M, 2);
System.out.println("M:" + MDec);
// 指数
// System.out.println("指数:" + (float)(2 >> (14)));
System.out.println("指数:" + Math.pow(2, EDec - 127));
System.out.println("尾数:" + (1.00 + (float) MDec / 8388608.00));
System.out.println("结果:" + (Math.pow(2, EDec - 127)) * (1.00 + (float) MDec / 8388608.00));
endValue.append(String.format("%.2f", (Math.pow(2, EDec - 127)) * (1.00 + (float) MDec / 8388608.00)));
System.out.println("最终结果:" + endValue);
}
private static String hexToBin(char charAt) {
// TODO Auto-generated method stub
switch (charAt) {
case '0':
return "0000";
case '1':
return "0001";
case '2':
return "0010";
case '3':
return "0011";
case '4':
return "0100";
case '5':
return "0101";
case '6':
return "0110";
case '7':
return "0111";
case '8':
return "1000";
case '9':
return "1001";
case 'A':
case 'a':
return "1010";
case 'B':
case 'b':
return "1011";
case 'C':
case 'c':
return "1100";
case 'D':
case 'd':
return "1101";
case 'E':
case 'e':
return "1110";
case 'F':
case 'f':
return "1111";
}
return null;
}
}