zoukankan      html  css  js  c++  java
  • byte流转字符串 字符串转byte流

        /// <summary>
        /// byte[]流转十六进制字符串 0x34---->"34"
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ToHexString(byte[] bytes)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
            char[] chars = new char[bytes.Length * 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                int b = bytes[i];//十六进制转化为十进制 0x34->52
                chars[i * 2] = hexDigits[b >> 4];
                chars[i * 2 + 1] = hexDigits[b & 0xF];
            }
            return new string(chars);
        }
        /// <summary>
        ///  字符串转byte    "34"---->52 (0x34)
        /// </summary>
        /// <param name="strAsccii"></param>
        /// <returns></returns>
        public static byte ConvertAscciiToByte(string strAsccii)
        {
            strAsccii = strAsccii.Trim();
            if (strAsccii.Length > 2 || strAsccii.Length < 1) return 0x00;
            return byte.Parse(strAsccii, System.Globalization.NumberStyles.AllowHexSpecifier);
        }

    测试代码:

        static void Main(string[] args)
        {
            Console.WriteLine("=========================");
            Console.WriteLine(" 源字符串为\"12345678\"");
            
            string nums = "12345678";
            byte[] bytes1=new byte[4];
            
            for (int n = 0; n < nums.Length/2; n++)
            {
                bytes1[n] = ConvertAscciiToByte(nums.Substring(n * 2, 2));
            }
            Console.WriteLine("12345678字符串转化为byte[]为 '" + bytes1[0].ToString("X") + " " + bytes1[1].ToString("X") + " "
                + bytes1[2].ToString("X") + " " + bytes1[3].ToString("X")+"'");
    
            string outStr = ToHexString(bytes1);
            Console.WriteLine("byte[]流转化为字符串为'"+outStr.ToString()+"'");
    
            Console.Read();
        }

    输出结果:

  • 相关阅读:
    线程中更新ui方法汇总
    Chromium Embedded Framework
    adb提取安装的apk
    下拉列表 Spinner
    更改activity切换方式
    左右页面滑动
    静态成员函数(面向对象的static关键字)
    静态数据成员(面向对象的static关键字)
    静态函数(面向过程的static关键字)
    静态局部变量(面向过程的static关键字)
  • 原文地址:https://www.cnblogs.com/kingkongv/p/2598140.html
Copyright © 2011-2022 走看看