C# 实现编码格式转换问题

ipkqmc 2011-08-13 04:07:59
一个winform程序中需要将用户输入内容的编码格式设置为Unicode
例如用户输入"你好,2008",则后台代码将其编码成”4f60597d0032003000300038“之后 再存入数据库
在下实在是忘了怎么写了,还请各位高手们指点一下,谢啦!
...全文
406 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
康少_小贱 2011-08-15
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 gefangliang 的回复:]
下面是C#汉字Unicode编码相互转换代码。

+展开
-C#using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
public class GB2312UnicodeConverter
{
/// <summary>
//……
[/Quote]

..
ipkqmc 2011-08-15
  • 打赏
  • 举报
回复
//编码格式转换
public static string ToUnicode(string str)
{
byte[] bts = Encoding.Unicode.GetBytes(str);
string r = "";
for (int i = 0; i < bts.Length; i += 2)
{
r += bts[i + 1].ToString("x").PadLeft(2, '0') + bts[i].ToString("x").PadLeft(2, '0');
}
return r;
}我的是这样转的,哈哈。。多谢各位帮忙
ipkqmc 2011-08-13
  • 打赏
  • 举报
回复
多谢楼上!!
心灵彩虹 2011-08-13
  • 打赏
  • 举报
回复
下面是C#汉字Unicode编码相互转换代码。

+展开
-C#using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
public class GB2312UnicodeConverter
{
/// <summary>
/// 汉字转换为Unicode编码
/// </summary>
/// <param name="str">要编码的汉字字符串</param>
/// <returns>Unicode编码的的字符串</returns>
public static string ToUnicode(string str)
{
byte[] bts = Encoding.Unicode.GetBytes(str);
string r = "";
for (int i = 0; i < bts.Length; i += 2) r += "\\u" + bts[i + 1].ToString("x").PadLeft(2, '0') + bts[i].ToString("x").PadLeft(2, '0');
return r;
}
/// <summary>
/// 将Unicode编码转换为汉字字符串
/// </summary>
/// <param name="str">Unicode编码字符串</param>
/// <returns>汉字字符串</returns>
public static string ToGB2312(string str)
{
string r = "";
MatchCollection mc = Regex.Matches(str, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
byte[] bts = new byte[2];
foreach(Match m in mc )
{
bts[0] = (byte)int.Parse(m.Groups[2].Value, NumberStyles.HexNumber);
bts[1] = (byte)int.Parse(m.Groups[1].Value, NumberStyles.HexNumber);
r += Encoding.Unicode.GetString(bts);
}
return r;
}
}
ipkqmc 2011-08-13
  • 打赏
  • 举报
回复
只知道在BS程序中可以用url编码格式,但在CS程序中就不知道该怎么解决了,总不能把BS中的类添加到这来用吧,各位高手们赶紧出来帮帮忙啊,谢啦

110,499

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧