[英]How to convert char in UTF-16 encoding to char in CP855 encoding?
[英]Java - Convert byte[] to char[]. The encoding is UTF-16
我需要在 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);
你可以試試這個:
byte[] b = ...
char[] c = new String(b, "UTF-16").toCharArray();
從String(byte[] bytes, String charsetName)
:
通過使用指定的字符集解碼指定的字節數組來構造一個新的
String
。
C# API:
public virtual char[] GetChars(byte[] bytes);
爪哇:
字節 [] 字節 = ...
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);
爪哇:
遍歷字節數組中所需的字節
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;
}
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.