无聊写写的小玩意,把一个float 浮点型的十进制数转换成十六进制数,暂示没有考虑负数的情况,代码如下:
public class Test1 {public static void main(String[] args) {System.out.println(new Test1().changeHx(972750.5f));}public String changeHx(float num) {String result;//获取整数部分int tempInt = (int) num;//获取小数部分float tempDecimal = getDecimal(num);result = IntNumToHex(tempInt) + "." + DecimalToHex(tempDecimal);return result;}//整数部分转换成十六进制public String IntNumToHex(int num) {String result = "";char c;if (num == 0) {result = "0";}else {while (num % 16 != 0 || num / 16 != 0) {int m = num % 16;if (m / 10 == 1) {c = (char)(65 + m % 10);}else {c= (char)(48 + m);}result = c + result;num = num / 16;}}return result;}//小数部分转换十六进制,不能精确转换的保留三位public String DecimalToHex(float num) {String result = "";char c;int i = 0;if(num == 0){result = "0";} else {while (num * 16 != 0 && i <= 2) {int m = (int)(num * 16);if (m / 10 == 1) {c = (char)(65 + m % 10);}else {c= (char)(48 + m);}result = result + c;num = getDecimal(num * 16);i++;}}return result;}//获取浮点数的小数部分public float getDecimal (Float num) {String str = String.valueOf(num);String [] nums = new String[2];nums = str.split("\\.");//获取小数部分float tempfloat;if (Integer.parseInt(nums[1]) == 0){tempfloat = 0;}else {String temp = "0."+nums[1];tempfloat = Float.parseFloat(temp);}return tempfloat;}}