How to convert byte[] to Byte[] and the other way around?

JavaArraysByteBoxing

Java Problem Overview


How to convert byte[] to Byte[] and also Byte[] to byte[], in the case of not using any 3rd party library?

Is there a way to do it fast just using the standard library?

Java Solutions


Solution 1 - Java

byte[] to Byte[] :

byte[] bytes = ...;
Byte[] byteObject = ArrayUtils.toObject(bytes);

Byte[] to byte[] :

Byte[] byteObject = new Byte[0];
byte[] bytes = ArrayUtils.toPrimitive(byteObject);

Solution 2 - Java

Byte class is a wrapper for the primitive byte. This should do the work:

byte[] bytes = new byte[10];
Byte[] byteObjects = new Byte[bytes.length];

int i=0;    
// Associating Byte array values with bytes. (byte[] to Byte[])
for(byte b: bytes)
   byteObjects[i++] = b;  // Autoboxing.

....

int j=0;
// Unboxing Byte values. (Byte[] to byte[])
for(Byte b: byteObjects)
    bytes[j++] = b.byteValue();
   

Solution 3 - Java

Java 8 solution:

Byte[] toObjects(byte[] bytesPrim) {
    Byte[] bytes = new Byte[bytesPrim.length];
    Arrays.setAll(bytes, n -> bytesPrim[n]);
    return bytes;
}

Unfortunately, you can't do this to convert from Byte[] to byte[]. Arrays has setAll for double[], int[], and long[], but not for other primitive types.

Solution 4 - Java

You could use the toPrimitive method in the Apache Commons lang library ArrayUtils class, As suggested here - https://stackoverflow.com/questions/6430841/java-byte-to-byte

Solution 5 - Java

byte[] toPrimitives(Byte[] oBytes)
{

    byte[] bytes = new byte[oBytes.length];
    for(int i = 0; i < oBytes.length; i++){
        bytes[i] = oBytes[i];
    }
    return bytes;

}

Inverse:

//byte[] to Byte[]
Byte[] toObjects(byte[] bytesPrim) {

    Byte[] bytes = new Byte[bytesPrim.length];
    int i = 0;
    for (byte b : bytesPrim) bytes[i++] = b; //Autoboxing
    return bytes;

}

Solution 6 - Java

From byte[] to Byte[]:

	byte[] b = new byte[]{1,2};
	Byte[] B = new Byte[b.length];
	for (int i = 0; i < b.length; i++)
	{
		B[i] = Byte.valueOf(b[i]);
	}

From Byte[] to byte[] (using our previously-defined B):

	byte[] b2 = new byte[B.length];
	for (int i = 0; i < B.length; i++)
	{
		b2[i] = B[i];
	}

Solution 7 - Java

If someone preferes Stream API over ordinary loops.

private Byte[] toObjects(byte[] bytes) {
    return IntStream.range(0, bytes.length)
            .mapToObj(i -> bytes[i])
            .toArray(Byte[]::new);
}

Solution 8 - Java

Step back. Look at the bigger picture. You're stuck converting byte[] to Byte[] or vice versa because of Java's strict type casing with something like this

> List< Byte> or >List

Now you have byte[] and Byte[] and have to convert. This will help.

Keep all your byte[]s in a list like this: List instead of List< Byte> or List. (byte is a primitive, byte[] is an object)

As you acquire bytes do this (networking socket example):

ArrayList<byte[]> compiledMessage = new ArrayList<byte[]>;
...
compiledMessage.add(packet.getData());

Then, when you want to put all your bytes in a single message, do this:

byte[] fromListOfNotByteArray (List<byte[]> list) {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ObjectOutputStream oos;
	try {
		oos = new ObjectOutputStream(baos);
		oos.writeObject(list);
	} catch (IOException e) {
		e.printStackTrace();
	}
	return baos.toByteArray();
}

That way, you can keep all your parts in List and your whole in byte[] without a bunch of crazy copy tasks in for loops with little baby byte[]s everywhere. ;)

Now you know -- teach others.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser926958View Question on Stackoverflow
Solution 1 - JavaLaCrampeView Answer on Stackoverflow
Solution 2 - JavaJuvanisView Answer on Stackoverflow
Solution 3 - JavaajbView Answer on Stackoverflow
Solution 4 - JavaGiannisView Answer on Stackoverflow
Solution 5 - JavajacktradesView Answer on Stackoverflow
Solution 6 - JavaDNAView Answer on Stackoverflow
Solution 7 - JavamkalmoView Answer on Stackoverflow
Solution 8 - JavaDavid UrryView Answer on Stackoverflow