如何将十六进制字符串转换为双精度? [英] How to convert an hexadecimal string to a double?
问题描述
我从BLE到我的手机a的范围为0x0000到0x01c2的十六进制值是 String
。为了将其绘制在图形中,我必须将其转换为 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.
推荐答案
您的值不是IEEE-754浮点值的十六进制表示-只是整数。因此,在删除开头的 0x前缀之后,只需将其解析为整数即可:
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);
}
}
如果您确实需要 double
在其他地方,您可以隐式转换:
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.
这篇关于如何将十六进制字符串转换为双精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!