Convert double to byte[] array

巧了我就是萌 提交于 2020-01-10 05:54:05

问题


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

Can I do it without using functions like doubleToLongBits()?


回答1:


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



回答2:


public static byte[] encode(double input, int size, int precision) {
    double tempInput = input;

    for (int i = 0; i < precision; i++) tempInput *= 10;

    int output = (int) tempInput;

    String strOut = String.format("%0"+size+"d", output);

    return strOut.getBytes();
}



回答3:


double doubleValue = 10.42123;
DecimalFormat df = new DecimalFormat("#.##");
String newDouble = df.format(doubleValue);
byte[] byteArray = (newDouble.replace(",", "")).getBytes();

for (byte b : byteArray) {
    System.out.println((char)b+"");
}



回答4:


This is what I got based on your inputs and it serves my purpose. Thanks for helping out!

static int formatDoubleToAscii(double d, int bytesToUse, int minPrecision, byte in[], int startPos) {

        int d1 = (int)(d * Math.pow(10, minPrecision));

        String t = String.format("%0"+bytesToUse+"d", d1).toString();
        System.out.println("d1 = "+ d1 + " t="+ t + " t.length=" + t.length());

        for(int i=0 ; i<t.length() ; i++, startPos++) {
            System.out.println(t.charAt(i));
            in[startPos] = (byte) t.charAt(i);
        }           

        return startPos;
    }



回答5:


ByteBuffer.allocate(8).putDouble()).array()


来源:https://stackoverflow.com/questions/13071777/convert-double-to-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!