我想同时使用7位和Unicode (UTF-8)对字符串进行编码。
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class Example{
public static void main(String[] args) throws Exception{
String originalMessage = "*ABC";
sevenBitEncoding(originalMessage);
unicodeEncoding(originalMessage);
}
private static void sevenBitEncoding(String originalMessage) {
char[] ch=originalMessage.toCharArray();
byte[] bytes = new String(ch).getBytes();
StringBuilder encodedMessage = new StringBuilder();
encodedMessage.append("[");
for(int i=0; i < bytes.length; i++) {
encodedMessage.append(bytes[i] + ",");
}
encodedMessage.replace(encodedMessage.length()-1, encodedMessage.length(), "]");
System.out.println("7-bit :" + encodedMessage.toString());
}
private static void unicodeEncoding(String originalMessage) {
byte[] bytes = originalMessage.getBytes(StandardCharsets.UTF_8);
// ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(originalMessage);
StringBuilder encodedMessage = new StringBuilder();
encodedMessage.append("[");
for(int i=0; i < bytes.length; i++) {
encodedMessage.append(bytes[i] + ",");
}
encodedMessage.replace(encodedMessage.length()-1, encodedMessage.length(), "]");
System.out.println("unicode:" + encodedMessage.toString());
}
}输出:
7-bit :[65,66,67]
unicode:[65,66,67]预期输出:
由于UTF-8使用基数16,因此UTF-8的期望值为2A。https://flaviocopes.com/unicode/
7-bit :[42,65,66,67]
unicode:[2A,41,42,43]有没有办法做到这一点?
发布于 2019-09-20 15:31:41
您正在做许多不必要的事情,比如无缘无故地从前一个字符串的char[]创建新字符串,以及在不带字符集参数的情况下调用getBytes(),这是一个禁忌。您还混淆了基础,并以某种方式认为"unicode使用十六进制“,这是没有意义的。
下面是如何使用给定的编码(例如UTF-8)显示字符串的字节数。
// Values are decimal, not hex
System.out.println(Arrays.toString("*ABC".getBytes(StandardCharsets.UTF8)));*ABC的字节在所有常见的编码中都是相同的,所以如果你想看到不同之处,你必须找到一种非常奇特的编码,或者使用不同编码的字符(例如,重音字符,如é,à,ä,ö,as,它们在UTF-8中需要2个字节)。
https://stackoverflow.com/questions/58023521
复制相似问题