类别:程序开发

日期:2020-03-03 浏览:3326 评论:0

1、字符串转16进制:

public static string GetStrFromChs(string s)
{
	if ((s.Length % 2) != 0)
	{
		s += " ";//空格
		//throw new ArgumentException("s is not valid chinese string!");
	}
 
	System.Text.Encoding chs = System.Text.Encoding.GetEncoding("gb2312");
 
	byte[] bytes = chs.GetBytes(s);
 
	string str = "";
 
	for (int i = 0; i < bytes.Length; i++)
	{
		str += string.Format("{0:X}", bytes[i]);
	}
 
	return str;
}


2、16进制转字符串

private string GetChsFromStr(string hex)
{
	if (hex == null)
	{
		//throw new ArgumentException("hex is null!");
	}
 
	if (hex.Length % 2 != 0)
	{
		hex += "20";//空格
		//throw new ArgumentException("hex is not a valid number!", "hex");
	}
 
	// 需要将 hex 转换成 byte 数组。
	byte[] bytes = new byte[hex.Length / 2];
 
	for (int i = 0; i < bytes.Length; i++)
	{
		try
		{
			// 每两个字符是一个 byte。
			bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
			System.Globalization.NumberStyles.HexNumber);
		}
		catch
		{
			// Rethrow an exception with custom message.
			throw new ArgumentException("hex is not a valid hex number!", "hex");
		}
	}
 
	// 获得 GB2312,Chinese Simplified。
	Encoding chs = System.Text.Encoding.GetEncoding("GB2312");
 
	return chs.GetString(bytes);
}


本文标题:C#字符串与16进制的相互转换
本文链接:https://vtzw.com/post/68.html
作者授权:除特别说明外,本文由 零一 原创编译并授权 零一的世界 刊载发布。
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。
 您阅读本篇文章共花了: 

历史上的今天
03月
03

 可能感兴趣的文章

评论区

发表评论 / 取消回复

必填

选填

选填

◎欢迎讨论,请在这里发表您的看法及观点。