我想将byte
中的每个byte[]
翻译成char
,然后将这些字符放在字符串上。这是一些数据库的所谓“二进制”编码。到目前为止,我能找到的最好的是这个巨大的样板:
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);
Java SE还是Apache Commons还有其他选择吗?我希望我能有这样的事情:
final Charset BINARY_CS = Charset.forName("BINARY");
String s = new String(bytes, BINARY_CS);
但是我不愿意写一个Charset及其编解码器(还)。在JRE或Apache Commons中是否有这样一个现成的二进制Charset?
答案 0 :(得分:9)
您可以将ASCII编码用于7位字符
String s = "Hello World!";
byte[] b = s.getBytes("ASCII");
System.out.println(new String(b, "ASCII"));
或8位ascii
String s = "Hello World! \u00ff";
byte[] b = s.getBytes("ISO-8859-1");
System.out.println(new String(b, "ISO-8859-1"));
修改
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"));
打印
ASCII => US-ASCII
US-ASCII => US-ASCII
ISO-8859-1 => ISO-8859-1
答案 1 :(得分:1)
您可以跳过char数组的步骤并放入String,甚至可以使用StringBuilder(如果您担心多线程,则使用StringBuffer)。我的例子显示了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();
我知道它没有回答你的其他问题。只是寻求帮助简化&#34;样板&#34;代码。
答案 2 :(得分:0)
有一个String构造函数,它接受一个字节数组和一个指定字节格式的字符串:
String s = new String(bytes, "UTF-8"); // if the charset is UTF-8
String s = new String(bytes, "ASCII"); // if the charset is ASCII
答案 3 :(得分:0)
您可以使用base64编码。 apache有一个实现
http://commons.apache.org/codec/
基地64 http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html