How to convert an hexadecimal string to a double?

大城市里の小女人 提交于 2019-12-11 15:18:00

问题


I'm getting the hexadecimal values of range 0x0000 to 0x01c2 from BLE to my phone a as String. In order to plot it in a graph, I have to convert it into double, for which I've tried this method but sadly it couldn't help in my case.

Here is the little modified code from the provided link:

String receivedData = CommonSingleton.getInstance().mMipsData; // 0x009a
long longHex = parseUnsignedHex(receivedData);
double d = Double.longBitsToDouble(longHex);

public static long parseUnsignedHex(String text) {
    if (text.length() == 16) {
        return (parseUnsignedHex(text.substring(0, 1)) << 60)
                | parseUnsignedHex(text.substring(1));
    }
    return Long.parseLong(text, 16);
}

Any further help would be much appreciated. Thanks in advance.


回答1:


Your value isn't a hex representation of an IEEE-754 floating point value - it's just an integer. So just parse it as an integer, after removing the leading "0x" prefix:

public class Test {
    public static void main(String[] args) {
        String text = "0x009a";

        // Remove the leading "0x". You may want to add validation
        // that the string really does start with 0x
        String textWithoutPrefix = text.substring(2);
        short value = Short.parseShort(textWithoutPrefix, 16);
        System.out.println(value);
    }
}

If you really need a double elsewhere, you can just implicitly convert:

short value = ...;
double valueAsDouble = value;

... but I'd try to avoid doing so unless you really need to.



来源:https://stackoverflow.com/questions/55295966/how-to-convert-an-hexadecimal-string-to-a-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!