通讯过程中16进制字符和byte[]/十进制和16进制转换(一)

复制代码
        /// <summary>
        /// 16进制字符转为字节流
        /// </summary>
        /// <param name="str"></param>
        /// <param name="fromBase"></param>
        /// <returns></returns>
        public static byte[] HexStringToByte(string str, int fromBase = 16)
        {
            str = str.Replace(" ", "");
            if ((str.Length % 2) != 0)
                str += "";
            byte[] bytes = new byte[str.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = Convert.ToByte(str.Substring(i * 2, 2), fromBase);
            }
            return bytes;
        }

       /// <summary>
       /// 整数转为16进制字符
       /// </summary>
       /// <param name="i"></param>
       /// <returns></returns>
       public static string Int16ToHexStr(Int16 i)
        {
            string fStr = "";
            fStr = PLC.Core.ByteToHexStr(BitConverter.GetBytes(i));
            return fStr;

        }
       /// <summary>
       /// 单浮点数转为16进制字符
       /// </summary>
       /// <param name="f"></param>
       /// <returns></returns>
        public static string FloatToHexStr(float f)
        {
            string fStr = "";
            fStr = PLC.Core.ByteToHexStr(BitConverter.GetBytes(f));
            return fStr;

        }
        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        static string ByteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

        /// <summary>
        /// 一个字节前后两位对调
        /// </summary>
        /// <param name="inputStr"></param>
        /// <returns></returns>
        public static string Start2ToEnd2(string inputHexStr)
        {
            string str = "";
            str = inputHexStr.Substring(2, 2) + inputHexStr.Substring(0, 2);
            return str;
        }
复制代码

 

posted @   echo-efun  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示