Convert byte [] to string

I have a bytearray of type byte [] with a length of 17 bytes, I want to convert this to a string and want to give this string for another comparison, but the output that I get is not in the format for verification, I use the method below to convert. I want to output as a string that is easy to check and give the same string for comparison.

byte[] byteArray = new byte[] {0,127,-1,-2,-54,123,12,110,89,0,0,0,0,0,0,0,0}; String value = new String(byteArray); System.out.println(value); 

Output: {nY

+4
source share
5 answers

What is the encoding? You must define it explicitly:

 new String(byteArray, Charset.forName("UTF-32")); //or whichever you use 

Otherwise, the result is unpredictable (from the String.String(byte[]) constructor of the JavaDoc):

Creates a new line by decoding the specified byte array using the default platform encoding

BTW I just tried it with UTF-8, UTF-16 and UTF-32 - they all give dummy results. A long series of 0 makes me believe that this is not really text. Where did you get this data?

UPDATE: I tried it with the all character sets available on my machine:

 for (Map.Entry<String, Charset> entry : Charset.availableCharsets().entrySet()) { final String value = new String(byteArray, entry.getValue()); System.out.println(entry.getKey() + ": " + value); } 

and no encoding creates anything close to human-readable text ... your input is not text.

+7
source

Use the following:

 byte[] byteArray = new byte[] {0,127,-1,-2,-54,123,12,110,89,0,0,0,0,0,0,0,0}; String value = Arrays.toString(byteArray); System.out.println(value); 

Your way out will be

 [0,127,-1,-2,-54,123,12,110,89,0,0,0,0,0,0,0,0] 
+5
source

Is this really coded text? If so, specify the encoding.

However, the data you receive does not look as if it is intended for text. It just looks like arbitrary binary data. If it is not text, I would recommend converting it to hex or base64, depending on the requirements. There you can use the base64 public domain encoder .

 String text = Base64.encodeBytes(byteArray); 

And decoding:

 byte[] data = Base64.decode(text): 
+4
source

not 100% sure if I get you right. Is this what you want?

 String s = null; StringBuffer buf = new StringBuffer(""); byte[] byteArray = new byte[] {0,127,-1,-2,-54,123,12,110,89,0,0,0,0,0,0,0,0}; for(byte b : byteArray) { s = String.valueOf(b); buf.append(s + ","); } String value = new String(buf); System.out.println(value); 
+1
source

Maybe you should specify the encoding:

 String value = new String(byteArray, "UTF-8"); 
0
source

Source: https://habr.com/ru/post/1396811/


All Articles