最近在项目中需要将十六进制转换为汉字,为了方便以后使用,上网搜了些资料写了个小工具。
汉字向十六进制转换
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
///
<summary>
/// 将汉字转换为Unicode
/// </summary>
/// <param name="stringText"></param>
/// <returns></returns>
private static string ToUnicode( string stringText)
{
string outStr = "" ;
if ( ! string .IsNullOrEmpty(stringText))
{
for ( int i = 0 ; i < stringText.Length; i ++ )
{
// 将中文字符转为10进制整数,然后转为16进制unicode字符
outStr += " \\u " + (( int )stringText[i]).ToString( " x " );
}
}
return outStr;
}
/// 将汉字转换为Unicode
/// </summary>
/// <param name="stringText"></param>
/// <returns></returns>
private static string ToUnicode( string stringText)
{
string outStr = "" ;
if ( ! string .IsNullOrEmpty(stringText))
{
for ( int i = 0 ; i < stringText.Length; i ++ )
{
// 将中文字符转为10进制整数,然后转为16进制unicode字符
outStr += " \\u " + (( int )stringText[i]).ToString( " x " );
}
}
return outStr;
}
十六进制向汉字转换
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
private
static
string
ToChinese(
string
utf16String)
{
// 转换后返回所转换
string [] splitString = new string [ 1 ];
splitString[ 0 ] = @" \u " ;
string [] utf16Strings = utf16String.Split(splitString, StringSplitOptions.RemoveEmptyEntries);
StringBuilder returnString = new StringBuilder();
foreach ( string ss in utf16Strings)
{
// ss是4个字符构成的一个字符编码,占用4个编码;
// string->byte[]->string
byte [] codes = new byte [ 2 ];
int code1, code2;
code1 = Convert.ToInt32(ss.Substring( 0 , 2 ), 16 );
code2 = Convert.ToInt32(ss.Substring( 2 ), 16 );
codes[ 0 ] = ( byte )code2;
codes[ 1 ] = ( byte )code1;
string getString = Encoding.Unicode.GetString(codes);
returnString.Append(getString);
}
return returnString.ToString();
}
{
// 转换后返回所转换
string [] splitString = new string [ 1 ];
splitString[ 0 ] = @" \u " ;
string [] utf16Strings = utf16String.Split(splitString, StringSplitOptions.RemoveEmptyEntries);
StringBuilder returnString = new StringBuilder();
foreach ( string ss in utf16Strings)
{
// ss是4个字符构成的一个字符编码,占用4个编码;
// string->byte[]->string
byte [] codes = new byte [ 2 ];
int code1, code2;
code1 = Convert.ToInt32(ss.Substring( 0 , 2 ), 16 );
code2 = Convert.ToInt32(ss.Substring( 2 ), 16 );
codes[ 0 ] = ( byte )code2;
codes[ 1 ] = ( byte )code1;
string getString = Encoding.Unicode.GetString(codes);
returnString.Append(getString);
}
return returnString.ToString();
}
效果