有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java数组将字节[]转换为字符[]。编码是UTF16

我需要在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);

共 (3) 个答案

  1. # 1 楼答案

    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;
        }
    }
    
  2. # 2 楼答案

    C#API:

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

    爪哇:

    byte[] byte = ...

    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);

    爪哇:

    Iterate through required bytes in the byte array

    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. # 3 楼答案

    你可以试试这个:

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

    ^{}

    Constructs a new String by decoding the specified array of bytes using the specified charset.