How would I take the first "n" elements of a byte array and convert them directly to a string?

I have a byte array of 1024 elements. I want to break this down into different string private members (for example, the first 9 bytes for the name, the next 12 bytes for userID, etc.).

Without having to turn the entire byte array into a string, and then using the substring method, is it possible to somehow turn the range of bytes into an array directly into a private member for my class?

eg.

myObject.name = byteArr[0-9]; myObject.userId = byteArr[10-21]; 
+5
source share
2 answers

Using:

 String myField = new String(myArray, start, end); 

where start will be 0 if you want to start from the beginning

+8
source

Use String constructor:

 public String(byte bytes[], int offset, int length, Charset charset) 

Example:

 myObject.name = new String(byteArr, 0, 10, Charset.defaultCharset()) 

Remember that bytes and characters are different in Java, and you must specify the correct conversion using the Charset class to avoid unexpected results.

+6
source

All Articles