Daniel Selvan
Daniel Selvan

Reputation: 1139

How to convert an hexadecimal string to a double?

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.

Upvotes: 0

Views: 1420

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502106

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.

Upvotes: 1

Related Questions