c# 常用编码转换
主要是Hex,Base64, Utf-8 和 byte[] 互转。
class Program
{
static void Main(string[] args)
{
string str = "abccba";
Console.WriteLine("原字符串:" + str);
byte[] byteData = Encoding.UTF8.GetBytes(str);
{
string hexlower = Byte2HexLower(byteData);
Console.WriteLine("转HEX:" + hexlower);
byte[] byteTemp = Hex2Byte(hexlower);
Console.WriteLine("转回字符串:" + Encoding.UTF8.GetString(byteTemp));
}
{
string base64 = Convert.ToBase64String(byteData).Replace("=", ",").Replace("+", "-").Replace("/", "_");
Console.WriteLine("转base64:" + base64);
byte[] byteTemp = Convert.FromBase64String(base64.Replace(",", "=").Replace("-", "+").Replace("_", "/"));
Console.WriteLine("转回字符串:" + Encoding.UTF8.GetString(byteTemp));
}
Console.ReadLine();
}
static string Byte2HexLower(byte[] byteData)
{
return BitConverter.ToString(byteData, 0).Replace("-", string.Empty).ToLower();
}
public static byte[] Hex2Byte(string hexString)
{
hexString = hexString.Replace(" ", "");
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
{
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return returnBytes;
}