C#串口助手实用工具类

using System;
using System.Text;
using System.Windows.Forms;

namespace MySSCOM
{
    internal class Utils
    {
        public static long getMMSystemTime()
        {
            return DateTime.Now.Ticks;
        }

        public static string getStrSystemTime()
        {
            string text = null;
            return DateTime.Now.ToString("[yyyy-MM-dd hh:mm:ss.fff]
");
        }

        public static byte StrHexToByte(string str)
        {
            byte result = 0;
            try
            {
                result = Convert.ToByte(str, 16);
                return result;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "错误提示");
                return result;
            }
        }

        public static byte[] StrHexArrToByte(string s)
        {
            _ = string.Empty;
            s = s.Replace(" ", "");
            byte[] array = new byte[s.Length / 2];
            int num = 0;
            for (int i = 0; i < s.Length; i += 2)
            {
                try
                {
                    array[num++] = Convert.ToByte(s.Substring(i, 2), 16);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "错误提示");
                }
            }
            return array;
        }

        public static string StrToHex(string s)
        {
            StringBuilder stringBuilder = new StringBuilder();
            byte[] bytes = Encoding.GetEncoding("GB18030").GetBytes(s);
            for (int i = 0; i < bytes.Length; i++)
            {
                stringBuilder.Append(Convert.ToString(bytes[i], 16).ToUpper().PadLeft(2, '0'));
                stringBuilder.Append(" ");
            }
            return stringBuilder.ToString();
        }

        public static string HexToStr(string s)
        {
            string empty = string.Empty;
            s = s.Replace(" ", "");
            byte[] array = new byte[s.Length / 2];
            int num = 0;
            for (int i = 0; i < s.Length; i += 2)
            {
                try
                {
                    array[num++] = Convert.ToByte(s.Substring(i, 2), 16);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "错误提示");
                }
            }
            empty = Encoding.Default.GetString(array);
            return empty.Replace("", "");
        }
    }
}

 

你可能感兴趣的