We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

# Floating Point to byte arrays re visited

prain asked
on
Medium Priority
249 Views
Last Modified: 2008-02-01
Ok. Recently some of you suggested how to convert a float number to a 4-byte array, and vice-versa.
and they worked well.

Now I am doing the same for 8-byte double numbers. I have writen the code and the class (some of the stuff is removed from this display).
Here is the class and the main() program. Can any experts in floating-point manipulation here tell why I am getting NaN when I ran this
example?

public class DoubleToByteArray
{
public static byte[] toByteArray(double doubleVal)
{
byte[] dByteArray = new byte[8];
long n = Double.doubleToLongBits(doubleVal);

for(int i = 0;  i < dByteArray.length;  i++)
{
dByteArray[i] = (byte)(n >> (i * 8) &0xFF);
}

return dByteArray;
}

public static double toDoubleValue(byte[] inBytes)
{
long n = 0;
for(int i = 0;  i < inBytes.length;  i++)
{
n |= ((inBytes[i] & 0377) << (i * 8));
}

double doubleValue = Double.longBitsToDouble(n);

return doubleValue;
}

public static void main(String [] args)
{
double aValue = -46633.91;

byte[] doubleBytes = ByteArray.toByteArray(aValue);

double recreatedValue = ByteArray.toDoubleValue(doubleBytes);

System.out.println("recreated : " + recreatedValue);
}
}
Comment
Watch Question

## View Solutions Only

Commented:
((inBytes[i] & 0377) << (i * 8)) is being calculated as an int.  You need to cast it to a long:

((long) (inBytes[i] & 0377) << (i * 8));

Not the solution you were looking for? Getting a personalized solution is easy.

Top Expert 2006
Commented:
Just a recommendation, prevent excessive multiplication :)

// DoubleToByteArray
for (int i = 0, shiftBy = 0; shiftBy < 64; shiftBy += 8) {
dByteArray[i++] = (byte) (n >> shiftBy & 0xFF);
}

// toDoubleValue
for (int i = 0, shiftBy = 0; shiftBy < 64; shiftBy += 8) {
n |= (long) (inBytes[i++] & 0xFF) << shiftBy;
}

Commented:
Thanks both of you. Hoomanv, thanks for the nice improved code.
Access more of Experts Exchange with a free account
##### Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the