Convert byte [] to string using binary encoding

I want to translate each byte from byte[] to char , and then put these characters in a string. This is the so-called "binary" encoding of some databases. So far, the best I could find is a huge template:

 byte[] bytes = ...; char[] chars = new char[bytes.length]; for (int i = 0; i < bytes.length; ++i) { chars[i] = (char) (bytes[i] & 0xFF); } String s = new String(chars); 

Is there another option from Java SE or maybe from Apache Commons? I wish I had something like this:

 final Charset BINARY_CS = Charset.forName("BINARY"); String s = new String(bytes, BINARY_CS); 

But I do not want to write Charset and their codecs (for now). Is there any ready-made binary encoding in the JRE or in Apache Commons?

+4
source share
4 answers

You can use ASCII encoding for 7-bit characters

 String s = "Hello World!"; byte[] b = s.getBytes("ASCII"); System.out.println(new String(b, "ASCII")); 

or 8-bit ascii

 String s = "Hello World! \u00ff"; byte[] b = s.getBytes("ISO-8859-1"); System.out.println(new String(b, "ISO-8859-1")); 

EDIT

 System.out.println("ASCII => " + Charset.forName("ASCII")); System.out.println("US-ASCII => " + Charset.forName("US-ASCII")); System.out.println("ISO-8859-1 => " + Charset.forName("ISO-8859-1")); 

prints

 ASCII => US-ASCII US-ASCII => US-ASCII ISO-8859-1 => ISO-8859-1 
+8
source

You can skip the char array step and put in String and even use StringBuilder (or StringBuffer if you are concerned about multithreading). My example shows StringBuilder.

 byte[] bytes = ...; StringBuilder sb = new StringBuilder(bytes.length); for (int i = 0; i < bytes.length; i++) { sb.append((char) (bytes[i] & 0xFF)); } return sb.toString(); 

I know that he does not answer your other question. Just trying to help simplify the "boilerplate" code.

+1
source

There is a String constructor that takes an array of bytes and a string defining the byte format:

 String s = new String(bytes, "UTF-8"); // if the charset is UTF-8 String s = new String(bytes, "ASCII"); // if the charset is ASCII 
0
source

You can use base64 encoding. There is an implementation executed by apache

http://commons.apache.org/codec/

Base 64 http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html

0
source

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


All Articles