将double转换为byte []数组

swa*_*wap 1 java double bytearray

如何在Java中将双字节数组转换为字节数组?我查看了许多其他帖子,但无法找到正确的方法.

Input = 65.43 
byte[] size = 6
precision = 2   (this might change based on input)

expected output (byte[]) = 006543
Run Code Online (Sandbox Code Playgroud)

我可以不使用像doubleToLongBits()这样的函数吗?

lyn*_*nks 13

真正doublebyte[]转换

double d = 65.43;
byte[] output = new byte[8];
long lng = Double.doubleToLongBits(d);
for(int i = 0; i < 8; i++) output[i] = (byte)((lng >> ((7 - i) * 8)) & 0xff);
//output in hex would be 40,50,5b,85,1e,b8,51,ec
Run Code Online (Sandbox Code Playgroud)

double 到BCD转换

double d = 65.43;
byte[b] output = new byte[OUTPUT_LENGTH];
String inputString = Double.toString(d);
inputString = inputString.substring(0, inputString.indexOf(".") + PRECISION);
inputString = inputString.replaceAll(".", "");
if(inputString.length() > OUTPUT_LENGTH) throw new DoubleValueTooLongException();
for(int i = inputString.length() - 1; i >= 0; i--) output[i] = (byte)inputString.charAt(i)
//output in decimal would be 0,0,0,0,6,5,4,3 for PRECISION=2, OUTPUT_LENGTH=8
Run Code Online (Sandbox Code Playgroud)


小智 8

ByteBuffer.allocate(8).putDouble(yourDouble).array()
Run Code Online (Sandbox Code Playgroud)