How would I take the first “n” elements of a byte array and convert them directly into a string?

不想你离开。 提交于 2019-12-12 10:58:32

问题


I have an array of bytes consisting of 1024 elements. I want to break this down into different string private members (e.g. first 9 bytes for name, next 12 bytes for userID, etc.).

Without having to turn the entire byte array into a string and then using a substring method, is there any way I can turn a range of bytes in the array directly into a private member for my class?

E.g.

myObject.name = byteArr[0-9];
myObject.userId = byteArr[10-21];

回答1:


Use:

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

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




回答2:


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 chars are different types in Java and you should specify correct conversion using Charset class to avoid unexpected results.



来源:https://stackoverflow.com/questions/29782300/how-would-i-take-the-first-n-elements-of-a-byte-array-and-convert-them-directl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!