将double转换为byte []数组
问题描述:
如何在Java中转换双字节数组?我看了很多帖子,但是找不到正确的方法。
How can I convert double to byte array in Java? I looked at many other posts, but couldn't figure out the right way.
Input = 65.43
byte[] size = 6
precision = 2 (this might change based on input)
expected output (byte[]) = 006543
不使用doubleToLongBits()等功能吗?
Can I do it without using functions like doubleToLongBits()?
答
真实 double
to byte []
转换
Real double
to byte[]
Conversion
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
double
to BCD Conversion
double
to BCD Conversion
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