I have a String representing a HEX value of a 64bit integer "0000000000EA6484". I need to transform it to the double value "0.9155962467" using Java. The instructions I 've been given is to format a 12.52 FP value of type int64_t (8 Bytes).
I found with some googling that the int64_t datatype in C++ is a signed integer. I have also found this post which seem to be relevant but confused me a bit.
Finally I have tried the following java code to see if I get the expected result but I get in both cases "7.5894195E-317". I am sure that either I have not understood how to solve the problem so I would appreciate some help, or that the expected output is wrong.
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] args) {
String hexString = "0000000000EA6484";//0.9155962467
long longValue = Long.parseLong(hexString, 16);
longValue = Long.parseUnsignedLong(hexString, 16);
System.out.println(longValue);
double doubleValue = Double.longBitsToDouble(longValue);
System.out.println(doubleValue);
byte[] bytes = hexStringToByteArray(hexString);
doubleValue = ByteBuffer.wrap(bytes).getDouble();
System.out.println(doubleValue);
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
}
return data;
}
}
As shown, 0000000000EA6484
represents 0.9155962467193603515625 in a Q40.24 format, not a floating-point format. This is a fixed-point format with 40 integer bits (including a sign bit) and 24 fraction bits. To convert it from the integer represented by those bits in a 64-bit integer format to the value represented by the same bits in the Q12.52 format, divide it by 2 24 : EA6484 16 = 15361156 10 , 15361156 / 2 24 = 0.9155962467193603515625. In Java, dividing the integer value by 16777216 (2 24 ) should suffice.
It appears whomever told you this was a 12.52 FP format was wrong. Even if there is some endian issue, or any other byte reordering, that would not explain the shifted position of the bits with respect to a 12.52 format, since it differs by a sub-byte fraction (52 bits − 24 bits = 28 bits, which is 3½ bytes).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.