【问题标题】:Hex to Cyrillic text十六进制到西里尔文字
【发布时间】:2021-05-28 13:55:44
【问题描述】:

我有像“D09FD0B5D180D0BDD0B8D0BA”这样的十六进制字节字符串,这是“Перник”。

对于西里尔字母的每个字母,我需要 2 个字节。

对于“П”,我需要“D0 9F”。

如果我使用:

char letter = (char) 1055; // this is "П"

我的问题是如何从十六进制“D0 9F”获取整数值“1055”。 或者如何从“D09FD0B5D180D0BDD0B8D0BA”转换为“Перник”。

【问题讨论】:

标签: java hex cyrillic


【解决方案1】:

您没有指定编码,但它似乎是 UTF-8,所以字符 П 没有编码为 041F(1055 年十月份),而是 D09F(53407 年十月份)。

另请注意,UTF-8 是一种可变长度编码,因此假设 2 字节/字符可能对西里尔字母有效,但不是一般情况。

import java.nio.charset.StandardCharsets;

public class Hex2String {
    public static String hex2String(String hex) {
        byte[] b=new byte[hex.length()/2];
        for (int i=0;i<b.length;i++) {
            b[i]=(byte) Integer.parseInt(hex, i*2, i*2+2, 16);
        }
        return new String(b, StandardCharsets.UTF_8);
    }
    
    public static void main(String[] args) {
        System.out.println(hex2String("D09FD0B5D180D0BDD0B8D0BA"));
    }
}

【讨论】:

  • @user15793316 不在 UTF-8 中,java 默认编码不是 UTF-8,而 OP 提供的十六进制字符串使用这种编码。 1055 是通用的 Unicode 值。
  • 或者:byte[] bytes = new BigInteger(hex, 16).toByteArray(); return new String(bytes, bytes[0]==0? 1: 0, hex.length()/2, StandardCharsets.UTF_8);
  • @Holger 这绝对更好!
猜你喜欢
  • 2019-05-17
  • 2021-10-28
  • 1970-01-01
  • 2023-03-14
  • 2011-12-09
  • 2014-02-07
  • 2010-10-04
  • 2017-09-13
  • 2018-07-26
相关资源
最近更新 更多