How to convert byte [] to Byte [], and vice versa?

How to convert byte [] to byte [], as well as byte [] to byte [] if you are not using any third-party library? Is there a way to do this quickly, just using the standard library?

+46
java arrays boxing byte
Oct 17 '12 at 22:27
source share
6 answers

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

 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(); 
+36
Oct. 17 '12 at 22:31
source share

You can use the toPrimitive method in the ArrayUtils class of the Apache Commons library. As suggested here - Java - Byte [] to byte []

+14
Nov 12 '13 at 9:56 on
source share

byte [] to Byte []:

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

Byte [] to byte []:

 Byte[] byteObject = new Byte[0]; byte[] bytes = ArrayUtils.toPrimitive(byteObject); 
+10
Sep 05 '16 at 11:38 on
source share

Java 8 solution:

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

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

+8
Jun 16 '14 at 10:50
source share

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]; } 
+4
17 Oct.
source share
 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; } 
+4
Jun 16 '14 at 22:43
source share



All Articles