C# 16进制转字符串,字符串转16进制

时间:2021-07-30 15:57:56

{

 //==========================================================
//16进制转字符串
public static byte[] HexToString(byte[] Str)
{
string String = Encoding.Default.GetString(Str);
byte[] str = new byte[Str.Length / ];
for (int i = ; i < str.Length; i++)
{
int temp = Convert.ToInt32(String.Substring(i * , ), );
str[i] = (byte)temp;
}
return str;
}
public static byte[] HexToString(string Str)
{
byte[] str = new byte[Str.Length / ];
for (int i = ; i < str.Length; i++)
{
int temp = Convert.ToInt32(Str.Substring(i * , ), );
str[i] = (byte)temp;
}
return str;
}
//字符串转16进制
public static byte[] StringToHex(byte[] Str)
{
string String = "";
for (int i = ; i < Str.Length; i++)
{
String += Encoding.Default.GetString(IntToHex(Str[i]));
}
return Encoding.Default.GetBytes(String);
}
public static byte[] StringToHex(string Str)
{
byte[] str = Encoding.GetEncoding("gb2312").GetBytes(Str);
return StringToHex(str);
}
private static byte[] IntToHex(byte num)
{
if (num > )
{
Console.WriteLine("大于两个字节数");
}
byte[] arr = new byte[];
int i = ;
while (true)
{
if (num % < )
{
arr[i] = (byte)((num % ) + );
}
else
{
switch (num % )
{
case : arr[i] = (byte)'A'; break;
case : arr[i] = (byte)'B'; break;
case : arr[i] = (byte)'C'; break;
case : arr[i] = (byte)'D'; break;
case : arr[i] = (byte)'E'; break;
case : arr[i] = (byte)'F'; break;
}
}
num /= ;
if (num == )
{
break;
}
i++;
}
if (arr[] == )
{
arr[] = ;
}
if (arr[] == )
{
arr[] = ;
}
byte temp = arr[];
arr[] = arr[];
arr[] = temp;
return arr;
}

}