当前位置:文档之家› C# byte[]与汉字、16进制字符的转换

C# byte[]与汉字、16进制字符的转换

C# byte[]与汉字、16进制字符的转换
C# byte[]与汉字、16进制字符的转换

c#中如何将十进制数的字符串转化成十六进制数的字符串

//

///把??字á?符¤?串??转áa换?成¨|16进?制?

///

///

///

///

private string StringToHex(string str, Encoding enc)

{

byte[] bytes = enc.GetBytes(str);

string result = string.Empty;

for (int i = 0; i < bytes.Length; i++)

{

result += "%" + Convert.ToString(bytes[i], 16);

}

return result;

}

///

///把??字á?符¤?串??转áa换?成¨|16进?制?字á?节¨2数oy组á¨|

///

///

///

private byte[] StringToHexbyte(string str)

{

str = str.Replace(" ", "");

if ((str.Length % 2) != 0)

str += "";

byte[] bytes = new byte[str.Length / 2];

for (int i = 0; i < bytes.Length; i++)

{

bytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);

}

return bytes;

}

///

///将?字á?节¨2数oy组á¨|转áa换?成¨|16进?制?字á?符¤?串??

///

///

///

private string ByteToHexString(byte[] bytes)

{

string str = string.Empty;

if (bytes != null)

{

for (int i = 0; i < bytes.Length; i++)

{

str += bytes[i].ToString("X2");

}

}

return str;

}

///

///将?汉o字á?转áa换?成¨|16进?制?

///

///汉o字á?

///编ਤ码?:êo如¨?“??UDF-8,ê?gb2312”?à

///是o?否¤?用??…?,ê???¥号?隔?开a

///

private string ToHex(string str, string charset, bool fenge)

{

if ((str.Length % 2) != 0) //加¨?一°?个?空?格?字á?符¤?

str += "";

Encoding enc = Encoding.GetEncoding(charset); //编ਤ码?类¤¨¤型¨a

byte[] bytes = enc.GetBytes(str); //转áa换?成¨|字á?节¨2数oy组á¨|string result = string.Empty;

//逐e一°?转áa换?

for (int i = 0; i < bytes.Length; i++)

{

result += string.Format("{0:X}", bytes[i]);

//是o?否¤?用??逗o号?隔?开a

if (fenge && i != bytes.Length - 1)

{

result += string.Format("{0}", ",");

}

}

return result;

}

///

///把??十o?六¢¨′进?制?转áa换?成¨|汉o字á?

///

///

///

///

private string HexToString(string hex, string charset)

{

hex = hex.Replace(" ", "");

hex = hex.Replace(",", "");

hex = hex.Replace("\\", "");

hex = hex.Replace("\n", "");

if ((hex.Length %2) != 0)

{

hex += "20"; //加¨?一°?个?空?格?字á?符¤?

}

byte[] bytes = new byte[hex.Length / 2];

for (int i = 0; i < bytes.Length; i++)

{

//两¢?个?16进?制?的ì?字á?符¤?占?一°?个?字á?节¨2

bytes[i] = byte.Parse(hex.Substring(i * 2, 2),NumberStyles.HexNumber) ;

}

Encoding enc = Encoding.GetEncoding(charset); //指?定?§编ਤ码?

return enc.GetString(bytes); //把??字á?节¨2数oy组á¨|转áa换?成¨|

}

相关主题
文本预览
相关文档 最新文档