Convert double to byte[] array

前端 未结 5 1569
灰色年华
灰色年华 2020-12-22 10:16

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
precisi         


        
5条回答
  •  不知归路
    2020-12-22 10:37

    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 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
    

提交回复
热议问题