开发者

How to efficiently convert byte array to string

开发者 https://www.devze.com 2023-02-01 08:27 出处:网络
I have a byte array of 151 bytes which is typically a record, The record needs to inserted in to a oracle database. In 151 byte of array range from 0 to 1 is a record id , 2 to 3 is an reference id ,

I have a byte array of 151 bytes which is typically a record, The record needs to inserted in to a oracle database. In 151 byte of array range from 0 to 1 is a record id , 2 to 3 is an reference id , 4 to 9 is a date value. The following data in an byte array is a date value. i want to convert it to string

byte[] b= {48,48,49,48,48,52};  // when converted to string it becomes 10042. 

new String(b开发者_运维问答);  // current approach

is there any way to efficiently to convert byte array of some range (Arrays.copyOfRange(b,0,5)) to string .


new String(b, 0 ,5);

See the API doc for more information.


Use the String(bytes[] bytes, int offset, int length) constructor: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#String(byte[], int, int)

new String(b, 0, 5);


If you need to create a string for each region in the record, I would suggest a substring approach:

byte[] wholeRecord = {0,1,2 .. all record goes here .. 151}
String wholeString = new String(wholeRecord);
String id = wholeString.substring(0,1);
String refId = wholeString.substring(1,3);
...

The actual offsets may be different depending on string encoding.

The advantage of this approach is that the byte array is only copied once. Subsequent calls to substring() will not create copies, but will simply reference the first copy with offsets. So you can save some memory and array copying time.


None of the answers here consider that you might not be using ASCII. When converting bytes to a string, you should always consider the charset.

new String(bytes, offset, length, charset);


and here fantastic way (not efficient) :)

    byte[] b = { 48, 48, 49, 48, 48, 52 };
    ByteArrayInputStream bais = new ByteArrayInputStream(b);

    BufferedReader buf = new BufferedReader(new InputStreamReader(bais));

    String s = buf.readLine();
    System.out.println(s);
0

精彩评论

暂无评论...
验证码 换一张
取 消