Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently convert byte array to string

Tags:

java

byte

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 .

like image 324
Dead Programmer Avatar asked Dec 29 '10 11:12

Dead Programmer


People also ask

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Can you store a byte array as a string?

String also has a constructor where we can provide byte array and Charset as an argument. So below code can also be used to convert byte array to String in Java. String str = new String(byteArray, StandardCharsets. UTF_8);

Can you convert byte into string?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable. The simplest way to do so is using valueOf() method of String class in java.


4 Answers

new String(b, 0 ,5);

See the API doc for more information.

like image 79
Michael Borgwardt Avatar answered Oct 09 '22 01:10

Michael Borgwardt


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);
like image 35
moinudin Avatar answered Oct 09 '22 01:10

moinudin


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.

like image 1
rodion Avatar answered Oct 08 '22 23:10

rodion


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);
like image 1
Drew Noakes Avatar answered Oct 09 '22 00:10

Drew Noakes