7 Replies Latest reply: Jan 18, 2008 4:55 PM by 807603

# How to take a negative hex double number into a Double variable?

Hi all,

I've got the problem of taking a string representing a negative double hex number like BFF0000000000000 (which is -1 in decimal) to a double type variable. Converting positive double hex numbers works fine, but as soon as i try to convert any negative number my program throws an exception.
conversion tool:
http://babbage.cs.qc.edu/IEEE-754/Decimal.html

I had to do this conversion method for float too, and noticed that in order to convert negative numbers too i had to make the parse with a higer type (long):

public static float hexToFloat(String hexValue)
{
float floatVal= 0.0f;

// Parse string interpreting data as a hex number into an int.
int decimalValue = (int)Long.parseLong(hexValue,16);

// Reinterpret the int variable's bits as a float type.
floatVal=Float.intBitsToFloat(decimalValue);

return floatVal;
}

But in the case of Double there is no higher type, any suggestions?.

• ###### 1. Re: How to take a negative hex double number into a Double variable?
Class Double
``public static double longBitsToDouble(long bits)``
P.S. Don't cast your long to an int.
• ###### 2. Re: How to take a negative hex double number into a Double variable?
raveko wrote:
// Parse string interpreting data as a hex number into an int.
int decimalValue = (int)Long.parseLong(hexValue,16);
I'm guessing the root of your problems is here.

There are two problems here. One, as sabre150 pointed out, is that you're casting the long to an int. Don't do that.

The second is what you mentioned: the parser interprets the number as unsigned, and as such, it's out of the range of a signed long. One possibility is to write your own parser (not hard). Another is to divide the string into two pieces, parse them separately, then combine them.
• ###### 3. Re: How to take a negative hex double number into a Double variable?
try this:
`````` BigInteger f = new BigInteger("437B69B4BACD05F1", 16);
System.out.println(  Double.longBitsToDouble(f.longValue()) );``````
• ###### 4. Re: How to take a negative hex double number into a Double variable?
zkropotkine wrote:
try this:
`````` BigInteger f = new BigInteger("437B69B4BACD05F1", 16);
System.out.println(  Double.longBitsToDouble(f.longValue()) );``````
• ###### 5. Re: How to take a negative hex double number into a Double variable?
zkropotkine wrote:
try this:
`````` BigInteger f = new BigInteger("437B69B4BACD05F1", 16);
System.out.println(  Double.longBitsToDouble(f.longValue()) );``````
There's this motto in medicine: "see one, do one, teach one"
• ###### 6. Re: How to take a negative hex double number into a Double variable?
``http://forum.java.sun.com/thread.jspa?threadID=5255592&tstart=0``