# How do I convert a decimal value to hexadecimal with double precision (64 bit)

Printable View

• 01-11-2008, 09:27 PM
SKaur
How do I convert a decimal value to hexadecimal with double precision (64 bit)
I want to convert a decimal value to a hex value with double precision. For example: 37.22 would convert to : 40429C28F5C28F5C

I found this webpage that does the conversion. IEEE-754 Floating-Point Conversion from Floating-Point to Hexadecimal

How would I code a function to do this in Java?

Thanks.

Sukhpreet Kaur
• 01-11-2008, 11:56 PM
afsina
Does Float.toHexString(float f) works for you? it is available Java 5 or further
• 01-12-2008, 12:50 AM
SKaur
Hi there,

Float.toHexString doesn't give me the required answer,

I have tried the following piece of code which gives result in 32-bit but I am looking for the result in 64-bit ....

public class HextoDbl
{
public static void main(String[] args)
{
float f = 37.22f;
int bits, s, e, m;

bits = Float.floatToIntBits(f);
s = ((bits >> 31) == 0) ? 1 : -1;
e = ((bits >> 23) & 0xff);
m = (e == 0) ?
(bits & 0x7fffff) << 1 :
(bits & 0x7fffff) | 0x800000;
String hexStr = Integer.toHexString(bits);
String leadingZeros = "";
System.out.println(hexStr.length()+" length, value: "+hexStr);
switch(hexStr.length()) {

case 7: leadingZeros = "0"; break;
case 6: leadingZeros = "00"; break;
case 5: leadingZeros = "000"; break;
case 4: leadingZeros = "0000"; break;
case 3: leadingZeros = "00000"; break;
case 2: leadingZeros = "000000"; break;
case 1: leadingZeros = "0000000"; break;
case 0: leadingZeros = "00000000"; break;

}
hexStr = leadingZeros + hexStr;
System.out.println( " Hexadecimal: " + hexStr);
}

}

Can anyone help please.

Thank you.

Regards,
Sukhpreet Kaur
• 01-12-2008, 07:01 AM
afsina
Use Double and Longs then. they are 64 bits.
• 01-12-2008, 08:34 AM
SKaur
Hi afsina,

I have used Long.toHexString(Double.doubleToLongBits(37.22)) and it gives me the following answer, 40429c2900000000... which is incomplete .... the complete answer should be 40429C28F5C28F5C.

Any suggestions please.

Thank you.

Regards,
Sukhpreet Kaur
• 01-12-2008, 09:40 PM
afsina
Long.toHexString(Double.doubleToLongBits(37.22d))
gives me 40429c28f5c28f5c
• 01-12-2008, 09:41 PM
afsina
Another way of doing is:

String s = String.format("&#37;x",Double.doubleToLongBits(37. 22d));
• 01-12-2008, 10:02 PM
SKaur
Hi afsina,

Thank you so much... it works...
I appreciate your help.

Thanx