Sunday, January 16, 2022

How to convert byte arrays to other data type and vice versa in Java

In this tutorial, we are going to learn how we can convert byte arrays to other data types like int, float, double, and vice versa. This conversion is the best practice for data transfer between different channels, I/O operations. 

By doing so, we can serialize and deserialize without changing the underlying data. If we want to create the binary files of different data types then first convert them to byte array and store them into a file.

Let's create a sample java class called ByteConverter.java

Convert Integer to a Byte array:

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public static byte[] toBytes(int intValue) {
        int times = Integer.SIZE / Byte.SIZE;
        return getAllocateByteBuffer(times).putInt(intValue).array();
    }
public static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN;
private static ByteBuffer getAllocateByteBuffer(int var) {
        return ByteBuffer.allocate(var).order(LITTLE_ENDIAN);
    }

Here, we are creating the toBytes() method which gets the allocated buffer and converts the Integer value to the Byte array. We are using ByteOrder as little-endian. Little-endian stores the least-significant byte at the smallest address. For more details on types of Endian visit Endianness.

Create a main method to test.

 public static void main(String[] args) {
        int a = 289;
        byte[] bytes = toBytes(a);
        System.out.println(Arrays.toString(bytes));
    }

Output:

[33, 1, 0, 0]

Convert Byte array to Integer:

  public static int toInteger(byte[] bytes) {
        return getByteBuffer(bytes).getInt();
    }
private static ByteBuffer getByteBuffer(byte[] bytes) {
        return ByteBuffer.wrap(bytes).order(LITTLE_ENDIAN);
    }
public static void main(String[] args) {
        byte[] bytes = {33, 1, 0, 0};
        int b = toInteger(bytes);
        System.out.println(b);
    }

Output:

289

Convert Double to Bytes and Vice versa:

 public static byte[] toBytes(double doubleValue) {
        int times = Double.SIZE / Byte.SIZE;
        return getAllocateByteBuffer(times).putDouble(doubleValue).array();
    }
public static double toDouble(byte[] bytes) {
        return getByteBuffer(bytes).getDouble();
    }
public static void main(String[] args) {
        double d = 45.56;
        byte[] doubleToBytes = toBytes(d);
        System.out.println("Double to bytes: "+ Arrays.toString(doubleToBytes));
        double bytesToDouble = toDouble(doubleToBytes);
        System.out.println("Bytes to Double: " + bytesToDouble);
    }

Convert Float to Bytes and vice versa:

public static byte[] toBytes(float floatValue) {
        int times = Float.SIZE / Byte.SIZE;
        return getAllocateByteBuffer(times).putFloat(floatValue).array();
    }
public static float toFloat(byte[] bytes) {
        return getByteBuffer(bytes).getFloat();
    }
public static void main(String[] args) {
        float f = 15.0f;
        byte[] floatToBytes = toBytes(f);
        System.out.println("Float to bytes: "+ Arrays.toString(floatToBytes));
        double bytesToFloat = toFloat(floatToBytes);
        System.out.println("Bytes to Float: " + bytesToFloat);
    }

Convert Integer array to byte array and vice versa:

 public static byte[] byteArray(int[] intArray) {
        int times = Integer.SIZE / Byte.SIZE;
        byte[] bytes = new byte[intArray.length * times];
        for (int i = 0; i < intArray.length; i++) {
            getByteBuffer(bytes, i, times).putInt(intArray[i]);
        }
        return bytes;
    }
 public static int[] intArray(byte[] byteArray) {
        int times = Integer.SIZE / Byte.SIZE;
        int[] ints = new int[byteArray.length / times];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = getByteBuffer(byteArray, i, times).getInt();
        }
        return ints;
    }
private static ByteBuffer getByteBuffer(byte[] bytes, int index, int times) {
        return ByteBuffer.wrap(bytes, index * times, times).order(LITTLE_ENDIAN);
    }
public static void main(String[] args) {
        int[] intArray = {3, 4, 6, 8};
        byte[] intByteArray = byteArray(intArray);
        System.out.println("Int array to byte array: "+ Arrays.toString(intByteArray));
        int[] byteArrayToIntArray = intArray(intByteArray);
        System.out.println("Byte array to Int array: "+ Arrays.toString(byteArrayToIntArray));
    }

Here, while converting from int array to byte array, we are looping through the int array and for each integer value, we are converting into bytes. and applying the reverse process while converting from byte array to integer array.

Convert Double array to Byte array and vice versa:

 public static byte[] byteArray(double[] doubleArray) {
        int times = Double.SIZE / Byte.SIZE;
        byte[] bytes = new byte[doubleArray.length * times];
        for (int i = 0; i < doubleArray.length; i++) {
            getByteBuffer(bytes, i, times).putDouble(doubleArray[i]);
        }
        return bytes;
    }
 public static double[] doubleArray(byte[] bytes) {
        int times = Double.SIZE / Byte.SIZE;
        double[] doubles = new double[bytes.length / times];
        for (int i = 0; i < doubles.length; i++) {
            doubles[i] = getByteBuffer(bytes, i, times).getDouble();
        }
        return doubles;
    }
public static void main(String[] args) {
        double[] doubleArray = {3.0, 4.0, 6.0, 8.0};
        byte[] doubleByteArray = byteArray(doubleArray);
        System.out.println("Double array to byte array: "+ Arrays.toString(doubleByteArray));
        double[] byteArrayToDoubleArray = doubleArray(doubleByteArray);
        System.out.println("Byte array to Double array: "+ Arrays.toString(byteArrayToDoubleArray));
    }

Convert Float array to Byte array and vice versa:

 public static byte[] byteArray(float[] floatArray) {
        int times = Float.SIZE / Byte.SIZE;
        byte[] bytes = new byte[floatArray.length * times];
        for (int i = 0; i < floatArray.length; i++) {
            getByteBuffer(bytes, i, times).putFloat(floatArray[i]);
        }
        return bytes;
    }
 public static float[] floatArray(byte[] bytes) {
        int times = Float.SIZE / Byte.SIZE;
        float[] floats = new float[bytes.length / times];
        for (int i = 0; i < floats.length; i++) {
            floats[i] = getByteBuffer(bytes, i, times).getFloat();
        }
        return floats;
    }
public static void main(String[] args) {
        float[] floatArray = {3.0f, 4.0f, 6.0f, 8.0f};
        byte[] floatByteArray = byteArray(floatArray);
        System.out.println("Float array to byte array: "+ Arrays.toString(floatByteArray));
        float[] byteArrayToFloatArray = floatArray(floatByteArray);
        System.out.println("Byte array to Float array: "+ Arrays.toString(byteArrayToFloatArray));

    }

The overall code implementation looks as below:

package io;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

public class ByteConverter {

    public static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN;

    public static void main(String[] args) {
        int i = 289;
        byte[] intToBytes = toBytes(i);
        System.out.println("Int to bytes: "+ Arrays.toString(intToBytes));
        int byteToInt = toInteger(intToBytes);
        System.out.println("Bytes to Int: " + byteToInt);
        double d = 45.56;
        byte[] doubleToBytes = toBytes(d);
        System.out.println("Double to bytes: "+ Arrays.toString(doubleToBytes));
        double bytesToDouble = toDouble(doubleToBytes);
        System.out.println("Bytes to Double: " + bytesToDouble);
        float f = 15.0f;
        byte[] floatToBytes = toBytes(f);
        System.out.println("Float to bytes: "+ Arrays.toString(floatToBytes));
        double bytesToFloat = toFloat(floatToBytes);
        System.out.println("Bytes to Float: " + bytesToFloat);
        int[] intArray = {3, 4, 6, 8};
        byte[] intByteArray = byteArray(intArray);
        System.out.println("Int array to byte array: "+ Arrays.toString(intByteArray));
        int[] byteArrayToIntArray = intArray(intByteArray);
        System.out.println("Byte array to Int array: "+ Arrays.toString(byteArrayToIntArray));
        double[] doubleArray = {3.0, 4.0, 6.0, 8.0};
        byte[] doubleByteArray = byteArray(doubleArray);
        System.out.println("Double array to byte array: "+ Arrays.toString(doubleByteArray));
        double[] byteArrayToDoubleArray = doubleArray(doubleByteArray);
        System.out.println("Byte array to Double array: "+ Arrays.toString(byteArrayToDoubleArray));
        float[] floatArray = {3.0f, 4.0f, 6.0f, 8.0f};
        byte[] floatByteArray = byteArray(floatArray);
        System.out.println("Float array to byte array: "+ Arrays.toString(floatByteArray));
        float[] byteArrayToFloatArray = floatArray(floatByteArray);
        System.out.println("Byte array to Float array: "+ Arrays.toString(byteArrayToFloatArray));

    }

    public static byte[] toBytes(int intValue) {
        int times = Integer.SIZE / Byte.SIZE;
        return getAllocateByteBuffer(times).putInt(intValue).array();
    }

    public static byte[] toBytes(double doubleValue) {
        int times = Double.SIZE / Byte.SIZE;
        return getAllocateByteBuffer(times).putDouble(doubleValue).array();
    }

    public static byte[] toBytes(float floatValue) {
        int times = Float.SIZE / Byte.SIZE;
        return getAllocateByteBuffer(times).putFloat(floatValue).array();
    }

    public static byte[] byteArray(int[] intArray) {
        int times = Integer.SIZE / Byte.SIZE;
        byte[] bytes = new byte[intArray.length * times];
        for (int i = 0; i < intArray.length; i++) {
            getByteBuffer(bytes, i, times).putInt(intArray[i]);
        }
        return bytes;
    }

    public static byte[] byteArray(double[] doubleArray) {
        int times = Double.SIZE / Byte.SIZE;
        byte[] bytes = new byte[doubleArray.length * times];
        for (int i = 0; i < doubleArray.length; i++) {
            getByteBuffer(bytes, i, times).putDouble(doubleArray[i]);
        }
        return bytes;
    }

    public static byte[] byteArray(float[] floatArray) {
        int times = Float.SIZE / Byte.SIZE;
        byte[] bytes = new byte[floatArray.length * times];
        for (int i = 0; i < floatArray.length; i++) {
            getByteBuffer(bytes, i, times).putFloat(floatArray[i]);
        }
        return bytes;
    }

    public static int toInteger(byte[] bytes) {
        return getByteBuffer(bytes).getInt();
    }

    public static double toDouble(byte[] bytes) {
        return getByteBuffer(bytes).getDouble();
    }

    public static float toFloat(byte[] bytes) {
        return getByteBuffer(bytes).getFloat();
    }

    public static int[] intArray(byte[] byteArray) {
        int times = Integer.SIZE / Byte.SIZE;
        int[] ints = new int[byteArray.length / times];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = getByteBuffer(byteArray, i, times).getInt();
        }
        return ints;
    }

    public static double[] doubleArray(byte[] bytes) {
        int times = Double.SIZE / Byte.SIZE;
        double[] doubles = new double[bytes.length / times];
        for (int i = 0; i < doubles.length; i++) {
            doubles[i] = getByteBuffer(bytes, i, times).getDouble();
        }
        return doubles;
    }

    public static float[] floatArray(byte[] bytes) {
        int times = Float.SIZE / Byte.SIZE;
        float[] floats = new float[bytes.length / times];
        for (int i = 0; i < floats.length; i++) {
            floats[i] = getByteBuffer(bytes, i, times).getFloat();
        }
        return floats;
    }

    private static ByteBuffer getByteBuffer(byte[] bytes) {
        return ByteBuffer.wrap(bytes).order(LITTLE_ENDIAN);
    }

    private static ByteBuffer getAllocateByteBuffer(int var) {
        return ByteBuffer.allocate(var).order(LITTLE_ENDIAN);
    }

    private static ByteBuffer getByteBuffer(byte[] bytes, int index, int times) {
        return ByteBuffer.wrap(bytes, index * times, times).order(LITTLE_ENDIAN);
    }
}

Share:

0 comments:

Blog Archive