C#
public static void Change_Action()
{
byte[] byData;
char[] charData; char[] charData1;
charData = ("我在家里等你.").ToCharArray();
charData1 = ("My pink half of the drainpipe.").ToCharArray();
Encoder e = Encoding.UTF8.GetEncoder();//获得实例
byData = new byte[charData.Length];
//int countbyte = e.GetByteCount(charData, 0, charData.Length, true);
//byData = new byte[countbyte];
e.GetBytes(charData, 0, charData.Length, byData, 0, true);
string bytestring = Encoding.UTF8.GetString(byData);
}
运行GetBytes报错信息为: 輸出位元組緩衝區太小,無法包含已編碼的資料,編碼方式 'Unicode (UTF-8)' 後援 'System.Text.Encoder ReplacementFallback'。
我将charData内容含有中文时转化为byte[],出错,byteData[]长度不够。因为charData的长度只有7,但是转化为byte[]长度为19,所以不能以charData的长度去设定byte[]长度。
int countbyte = e.GetByteCount(charData, 0, charData.Length, true);可以得到char转byte所需长度为多少。
但是charData1英文转换不报错,得到内容也不缺少。
中文和英文char转换byte长度不一样,为了严谨,使用 Encoder.GetByteCount()来避免报错
byte[]转换为char[]也同样注意两者转换过程中长度的变化,为了严谨,使用Decoder.GetCharCount()来避免报错
Decoder decoder = Encoding.UTF8.GetDecoder();
int charSize = decoder.GetCharCount(bytes, 0, bytes.Length);