号码字符串与BCD编码互转 c#

/// <summary>
        /// 把号码用BCD进行压缩编码。
        /// </summary>
        /// <param name="Num8BitByte">The num8 bit byte.</param>
        /// <returns></returns>
        public static byte[] ByteArrayToBCD(byte[] Num8BitByte)//8位的ascii码
        {
            byte[] Num4bitByte = new byte[8];

            Num4bitByte = BitConverter.GetBytes(0xffffffffffffffff);
            for (int i = 0; i<Num8BitByte.Length; i++)
            {
                byte num =Convert.ToByte(Num8BitByte[i] - 0x30);
                if (i % 2 == 0)
                {
                    Num4bitByte[i / 2] = Convert.ToByte((Num4bitByte[i / 2] & 0xF0) | num);
                }
                else
                {
                    Num4bitByte[i / 2] = Convert.ToByte((Num4bitByte[i / 2] &0x0F)| (num << 4));
                }
                  
            }
            
            return Num4bitByte;
        }

        /// <summary>
        /// BCDs to string.
        /// </summary>
        /// <param name="bcdNum">The BCD num.</param>
        /// <returns></returns>
        public static string bcdToString(byte[] bcdNum)
        {
            string retString="";
            byte[] byteChar = new byte[bcdNum.Length];
            byteChar = BitConverter.GetBytes(0xffffffffffffffff);
            byte tempHigh=0,tempLow=0;
            int i = 0;
            while (tempHigh != 0x0F && tempLow != 0xF0)
            {
                tempHigh = Convert.ToByte(bcdNum[i] & 0xF0);//取出高四位;
                tempHigh = Convert.ToByte(tempHigh >> 4);
                tempLow = Convert.ToByte((bcdNum[i] & 0x0F) << 4);
                byteChar[i] = Convert.ToByte(tempLow | tempHigh);
                i++;
            } 
            string[] HexString=BitConverter.ToString(byteChar).Trim().Split('-');
            foreach (string str in HexString)
            {
                retString += str.Trim();
            }
            int LastIndex = retString.IndexOf('F');
            return retString = retString.Substring(0, LastIndex);
        }

posted @   94cool  阅读(2088)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2013-03-06 c# Winform UI异步委托
2013-03-06 GPS经纬度判断是否在圆、多边形、矩形内
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示