Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best and efficient way to convert double value into a byte array in Java [closed]

I'm working on a low latency system and need a solution to convert a double number to byte array but with precision for decimal numbers. I need to consider there should be less object creation within the solution. Also, I'm getting value as double.

My current implementation is somewhat like

int offset = 0;
double d = 1211.11;
long integerPart = (long) d;
byte[] b = new byte[16];

offset += addToByteArray(integerPart, b, offset); 
//implementation to add each digit to byte array, returns new offset

int lengthDecimal = 16 - offset;
if(lengthDecimal > 0)
b[offset++] = '.';
long tmp = 1;

for(int i=0; i<lengthDecimal; i++){
 tmp = tmp * 10;
 int digit = (int)(((long) (d * tmp)) % 10);
 b[offset++] = (byte) ('0' + digit);
}

Then the byte array is manipulated to trim later zeros and '.' if required.

The problem is if I check the byte array, I don't find the exact digits. Since, I'm using double, the precision of decimal point is lost while working.

I've searched and found everywhere to use BigDecimal. The use of BigDecimal seems to work fine but I'm worried about the performance and number of objects created as this part of the code is hit frequently.

I've also tried to work with String like this

String doubleNumber = Double.toString(d);
long fractionalPart = 0;

offset += addToByteArray(integerPart, b, offset); 
if(doubleNumber.substring(doubleNumber.indexOf(".")).length() > 0) {
  fractionalPart = Long.valueOf(doubleNumber.substring(doubleNumber.indexOf(".") + 1));
  b[offset++] = '.';
  offset += addToByteArray(fractionalPart, b, offset);
}

Please suggest me the best approach for the purpose.

like image 256
darkapple Avatar asked Dec 27 '12 23:12

darkapple


People also ask

Can we convert double to byte in Java?

Casting double to byte Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator.

Which of the following ways is correct to convert a byte into long object?

The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes).

How do you convert a double to a whole number in Java?

round() method converts the double to an integer by rounding off the number to the nearest integer. For example – 10.6 will be converted to 11 using Math. round() method and 1ill be converted to 10 using typecasting or Double. intValue() method.


1 Answers

byte[] bytes = new byte[8];
java.nio.ByteBuffer.wrap(bytes).putDouble(yourDouble);
like image 71
izilotti Avatar answered Sep 24 '22 14:09

izilotti