Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 966
user926958 Avatar asked Oct 17 '12 22:10

user926958


People also ask

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.

What does byte [] do in Java?

A byte in Java is 8 bits. It is a primitive data type, meaning it comes packaged with Java. Bytes can hold values from -128 to 127. No special tasks are needed to use it; simply declare a byte variable and you are off to the races.

How do you convert bytes to long objects?

The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes). longValue();


2 Answers

byte[] to Byte[] :

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

Byte[] to byte[] :

Byte[] byteObject = new Byte[0]; byte[] bytes = ArrayUtils.toPrimitive(byteObject); 
like image 182
LaCrampe Avatar answered Oct 07 '22 10:10

LaCrampe


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(); 
like image 45
Juvanis Avatar answered Oct 07 '22 10:10

Juvanis