最近一个项目中,同事用的是C往SQLite写入的数据,保存中文时用的是双字节的ASCII码。而我的程序是用C#写的,一开始没注意到这个问题,所以读取中文一直乱码。 在C#中好像没有找到合适的函数可以直接将双字节的ASCII码转成中文,然后考虑是否通过反向的思路看看是否可以将字节码转回中文,首先是通过SQLite的hex()函数将中文数据直接按16进制串返回。
SELECT transaction_serial_number,card_number,update_time,deal_result,hex(customer_name) as customer_name, ....
然后再将数据16进制转回10进制,再转回中文
/// <summary>
/// 将16进制串转10进制字节数组
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static byte[] HexStringToByteArray(string input)
{
input = input.Replace(" ", "").Trim().ToUpper();
byte[] buffer = new byte[input.Length / 2];
for (int i = 0; i < input.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(input.Substring(i, 2), 16);
return buffer;
}
public static string HexToGB2312(string source)
{
byte[] bytes = HexStringToByteArray(source);
return Encoding.GetEncoding("GB2312").GetString(bytes);
}
HexConverter.HexToGB2312(reader["customer_name"].ToString());
来源:oschina
链接:https://my.oschina.net/zhuanghamiao/blog/4716104