nawara
nawara

Reputation: 1167

How to convert a byte array to double array

I would sent a double array from Ancroid client to Java server. For this puropose, I starts to convert int to byte array on client side then encode it with Base64

Now , I want to know how to perform the reverse operation , e.g. converting back the received byte array[]to double array []

I used this method on the client side

    public byte[] toByteArray(double[] from) {
    byte[] output = new byte[from.length*Double.SIZE/8]; 
    int step = Double.SIZE/8;
    int index = 0;
    for(double d : from){
        for(int i=0 ; i<step ; i++){
            long bits = Double.doubleToLongBits(d); 
            byte b = (byte)((bits>>>(i*8)) & 0xFF);

            int currentIndex = i+(index*8);
            output[currentIndex] = b;
        }
        index++;
    }
    return output;
}

Upvotes: 1

Views: 1190

Answers (1)

L. Quastana
L. Quastana

Reputation: 1336

Try it :

public static double[] toDoubleArray(byte[] byteArray){
        int times = Double.SIZE / Byte.SIZE;
        double[] doubles = new double[byteArray.length / times];
        for(int i=0;i<doubles.length;i++){
            doubles[i] = ByteBuffer.wrap(byteArray, i*times, times).getDouble();
        }
        return doubles;
    }

Upvotes: 1

Related Questions