首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将字符串编码为UTF-8和7位编码

将字符串编码为UTF-8和7位编码
EN

Stack Overflow用户
提问于 2019-09-20 15:16:27
回答 1查看 482关注 0票数 0

我想同时使用7位和Unicode (UTF-8)对字符串进行编码。

代码语言:javascript
复制
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());
    }
}

输出:

代码语言:javascript
复制
7-bit  :[65,66,67]
unicode:[65,66,67]

预期输出:

由于UTF-8使用基数16,因此UTF-8的期望值为2A。https://flaviocopes.com/unicode/

代码语言:javascript
复制
7-bit  :[42,65,66,67]
unicode:[2A,41,42,43]

有没有办法做到这一点?

EN

回答 1

Stack Overflow用户

发布于 2019-09-20 15:31:41

您正在做许多不必要的事情,比如无缘无故地从前一个字符串的char[]创建新字符串,以及在不带字符集参数的情况下调用getBytes(),这是一个禁忌。您还混淆了基础,并以某种方式认为"unicode使用十六进制“,这是没有意义的。

下面是如何使用给定的编码(例如UTF-8)显示字符串的字节数。

代码语言:javascript
复制
// Values are decimal, not hex
System.out.println(Arrays.toString("*ABC".getBytes(StandardCharsets.UTF8)));

*ABC的字节在所有常见的编码中都是相同的,所以如果你想看到不同之处,你必须找到一种非常奇特的编码,或者使用不同编码的字符(例如,重音字符,如é,à,ä,ö,as,它们在UTF-8中需要2个字节)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58023521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档