LaJiFenLei/WasteHexTest/Program.cs

95 lines
2.4 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// See https://aka.ms/new-console-template for more information
using System.Text;
Console.WriteLine("Hello, World!");
string hextstr = "31 31 31 31 31 31 31 40 31 31 31 31 31 40 B3 F8 D3 E0 C0 AC BB F8 40 31 36 36 2E 35 0D 0A ";
hextstr = hextstr.Replace(" ", "");
byte[] bytes = Encoding.UTF8.GetBytes(hextstr);
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var a = GetChsFromHex(hextstr);
Console.WriteLine(a);
/// <summary>
/// 16进制转汉字
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
static string GetChsFromHex(string hex)
{
if (hex == null)
return "";
if (hex.Length % 2 != 0)
{
hex += "20";//空格
}
// 需要将 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
{
}
}
// 获得 GB2312Chinese Simplified。
Encoding chs = Encoding.GetEncoding("gb2312");
return chs.GetString(bytes);
}
/// <summary>
/// 16进制转10进制
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
static long HextToDec(string hex)
{
char[] nums = hex.ToCharArray();
long total = 0;
try
{
for (int i = 0; i < nums.Length; i++)
{
String strNum = nums[i].ToString().ToUpper();
switch (strNum)
{
case "A":
strNum = "10";
break;
case "B":
strNum = "11";
break;
case "C":
strNum = "12";
break;
case "D":
strNum = "13";
break;
case "E":
strNum = "14";
break;
case "F":
strNum = "15";
break;
default:
break;
}
double power = Math.Pow(16, Convert.ToDouble(nums.Length - i - 1));
total += Convert.ToInt64(strNum) * Convert.ToInt64(power);
}
}
catch (System.Exception ex)
{
string strErorr = ex.ToString();
return 0;
}
return total;
}