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

 

{

 //==========================================================
        //16进制转字符串
        public static byte[] HexToString(byte[] Str)
        {
            string String = Encoding.Default.GetString(Str);
            byte[] str = new byte[Str.Length / 2];
            for (int i = 0; i < str.Length; i++)
            {
                int temp = Convert.ToInt32(String.Substring(i * 2, 2), 16);
                str[i] = (byte)temp;
            }
            return str;
        }
        public static byte[] HexToString(string Str)
        {
            byte[] str = new byte[Str.Length / 2];
            for (int i = 0; i < str.Length; i++)
            {
                int temp = Convert.ToInt32(Str.Substring(i * 2, 2), 16);
                str[i] = (byte)temp;
            }
            return str;
        }
        //字符串转16进制
        public static byte[] StringToHex(byte[] Str)
        {
            string String = "";
            for (int i = 0; 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 > 255)
            {
                Console.WriteLine("大于两个字节数");
            }
            byte[] arr = new byte[2];
            int i = 0;
            while (true)
            {
                if (num % 16 < 10)
                {
                    arr[i] = (byte)((num % 16) + 48);
                }
                else
                {
                    switch (num % 16)
                    {
                        case 10: arr[i] = (byte)'A'; break;
                        case 11: arr[i] = (byte)'B'; break;
                        case 12: arr[i] = (byte)'C'; break;
                        case 13: arr[i] = (byte)'D'; break;
                        case 14: arr[i] = (byte)'E'; break;
                        case 15: arr[i] = (byte)'F'; break;
                    }
                }
                num /= 16;
                if (num == 0)
                {
                    break;
                }
                i++;
            }
            if (arr[0] == 0)
            {
                arr[0] = 48;
            }
            if (arr[1] == 0)
            {
                arr[1] = 48;
            }
            byte temp = arr[0];
            arr[0] = arr[1];
            arr[1] = temp;
            return arr;
        }

 

}

posted @ 2019-12-02 11:39  YZFHKMS-X  阅读(8067)  评论(1编辑  收藏  举报