Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array of byte to String in Java? [duplicate]

How can I convert a array of bytes to String without conversion?.

I tried:

  String doc=new String( bytes);

But the doc file is not the same than the bytes (the bytes are binary information). For example:

  String doc=new String( bytes);
  byte[] bytes2=doc.getBytes();

bytes and bytes2 are different.

PS: UTF-8 Does not work because it convert some bytes in different values. I tested and it does not work.

PS2: And no, I don't want BASE64.

like image 685
magallanes Avatar asked Jul 10 '13 15:07

magallanes


People also ask

Can we convert byte to string in Java?

Given a Byte value in Java, the task is to convert this byte value to string type. 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.

Can we convert byte to double in Java?

Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator.

Can we convert string to byte array in Java?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.


1 Answers

You need to specify the encoding you want e.g. for UTF-8

String doc = ....
byte[] bytes = doc.getBytes("UTF-8");
String doc2 = new String(bytes, "UTF-8");

doc and doc2 will be the same.

To decode a byte[] you need to know what encoding was used to be sure it will decode correctly.

like image 97
Peter Lawrey Avatar answered Oct 07 '22 13:10

Peter Lawrey