首页 > 其他 > 详细

串口发送16进制字节数组

时间:2014-02-27 06:15:50      阅读:429      评论:0      收藏:0      [点我收藏+]

        /// <summary>
        /// 字符串转16进制字节数组
        /// </summary>
        /// <param name="hexString">例如20 1A</param>
        /// <returns></returns>
        public static byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                //for (int i = 0; i < bytes.Length; i++)
                //{
                //    returnStr += bytes[i].ToString("X2") + " ";
                //}
                foreach (byte byteData in bytes)
                {
                    returnStr += byteData.ToString("X2") + " ";//X为 十六进制 2为 每次都是两位数 比如0x0A
                }
            }
            return returnStr.Trim();
        }

串口字节发送,

            byte[] SendBuf = strToHexByte(textBox3.Text);
           
            _serialPort.Write(SendBuf, 0, SendBuf.Length);

串口字符串发送

          _serialPort.Write(textBox2.Text + "\r\n");        

串口发送16进制字节数组,布布扣,bubuko.com

串口发送16进制字节数组

原文:http://www.cnblogs.com/liujicai/p/3568678.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!