双十六进制字符串和后面 [英] Double to Hex String and Back

查看:180
本文介绍了双十六进制字符串和后面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中将double转换为十六进制字符串非常简单。但是我该怎么做呢?我的代码在下面,我已经注意到一个 NumberFormatException 被抛出(大约2/3秒)。

  public class HexToDoubleTest {
public static void main(String args []){

//这是起始double值
double doubleInput = -9.156013e-002;

//将起始值转换为长
long中的等效值double doubleLong = Double.doubleToRawLongBits(doubleInput);

//将long转换为字符串
String doubleAsString = Long.toHexString(doubleAsLong);

//打印字符串
System.out.println(doubleAsString);

//尝试将字符串解析为long
// !!!这将失败与NumberFormatException !!!
long doubleAsLongReverse = Long.parseLong(doubleAsString,16);

//将long返回到原来的double
double doubleOutput = Double.longBitsToDouble(doubleAsLongReverse);

//确认值匹配
assert(doubleInput == doubleOutput);

}
}

使用 Double.valueOf 以相同的方式失败。



编辑:我已经在网上完成了几次搜索,发现了一些非常不方便的解决方案。例如:使用 BigInteger 似乎过于杀伤。必须有一个更好的方法!

解决方案

您可以将String分解成两半并解析每个,但我认为是最简单的。

  long doubleAsLongReverse = new BigInteger(doubleAsString,16).longValue(); 


It's fairly simple to convert a double to a hexadecimal string in Java. But how do I do the reverse? My code is below and I've noted where a NumberFormatException is thrown (about 2/3rds down).

public class HexToDoubleTest {
    public static void main( String args[] ) {

        // This is the starting double value
        double doubleInput = -9.156013e-002;

        // Convert the starting value to the equivalent value in a long
        long doubleAsLong = Double.doubleToRawLongBits( doubleInput );

        // Convert the long to a String
        String doubleAsString = Long.toHexString( doubleAsLong );

        // Print the String
        System.out.println( doubleAsString );

        // Attempt to parse the string back as a long
        // !!! This fails with a NumberFormatException !!!
        long doubleAsLongReverse = Long.parseLong( doubleAsString, 16 );

        // Convert the long back into the original double
        double doubleOutput = Double.longBitsToDouble( doubleAsLongReverse );

        // Confirm that the values match
        assert( doubleInput == doubleOutput );

    }
}

Using Double.valueOf fails in the same manner.

Edit: I've done a few searches on the web already and found some very inelegant solutions. For example: Using a BigInteger seems like overkill. There's got to be a better way!

解决方案

You can break the String into two halves and parse each one, but I think this is the simplest.

long doubleAsLongReverse = new BigInteger(doubleAsString, 16).longValue();

这篇关于双十六进制字符串和后面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆