【问题标题】:Java - Convert byte[] to char[]. The encoding is UTF-16Java - 将 byte[] 转换为 char[]。编码为 UTF-16
【发布时间】:2015-09-06 07:42:41
【问题描述】:

我需要在 Java 中将 byte[] 转换为 char[]。 使用的 Unicode 编码是 UTF-16。

简而言之,我需要一个相当于 c# 的 Java

UnicodeEncoding.Unicode.GetChars(byte[] bytes);

另外,我只需要将 byte[] 的一部分转换为 char[]

public virtual char[] GetChars(byte[] bytes, int index, int count);

【问题讨论】:

  • 你为什么不喜欢UTF-8UTF-16 总是不必要地占用至少两个字节(即使不是绝对必要 - 即使 unicode 代码点适合单个字节)。
  • 我正在读取的值已经以 UTF-16 编码。

标签: java arrays character-encoding type-conversion utf-16


【解决方案1】:

你可以试试这个:

byte[] b = ...
char[] c = new String(b, "UTF-16").toCharArray();

来自String(byte[] bytes, String charsetName)

通过使用指定的字符集解码指定的字节数组来构造一个新的String

【讨论】:

    【解决方案2】:

    C# API:

    public virtual char[] GetChars(byte[] bytes);

    Java:

    字节[] 字节 = ...

    char[] char = new String(byte, "UTF-16").toCharArray();

    返回 char[] 的 Java 方法:

    public static char[] getCharsFromBytes(byte[] bytes, String type) {
        try {
            String byteConvert = new String(bytes, "UTF-16");
            return byteConvert.toCharArray();
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(DataTypeUtil.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
    

    C# API:

    public virtual char[] GetChars(byte[] bytes, int index, int count);

    Java:

    遍历字节数组中需要的字节

    public static char[] getCharsFromBytes(byte[] bytes, int index, int count) {
        char[] charArr = getCharsFromBytes(bytes);
        char[] result = new char[count];
        for (int i = 0; i < count; i++) {
            result[i] = charArr[i + startIndex];
        }
        return result;
    }
    

    【讨论】:

      【解决方案3】:
      public static char[] GetChars(byte[] bytes, int index, int count) {
          try {
              return new String(java.util.Arrays.copyOfRange(bytes,index,index+count), "UTF-16").toCharArray();
          } catch (java.io.UnsupportedEncodingException e) {
              assert false: "Your JRE is broken (UTF-16 not supported)";
              return null;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-30
        • 2017-09-24
        • 1970-01-01
        • 2012-06-12
        • 2011-07-22
        • 2015-09-21
        • 2021-06-15
        相关资源
        最近更新 更多