进制转换及效验

 /// <summary>
    /// 完成bit的位操作,和校验的方法,byte[]操作
    /// </summary>
    public class BitByteOper
    {
        //index从0开始 
        //获取取第index位 
        public static int GetBit(byte b, int index) { return ((b & (1 << index)) > 0) ? 1 : 0; }
        //将第index位设为1 
        public static byte SetBit(byte b, int index) { return (byte)(b | (1 << index)); }
        //将第index位设为0 
        public static byte ClearBit(byte b, int index) { return (byte)(b & (byte.MaxValue - (1 << index))); }
        //将第index位取反 
        public static byte ReverseBit(byte b, int index) { return (byte)(b ^ (byte)(1 << index)); }

        //public static Int16 JiaoYanHe(byte[] memorySpage)
        //{
        //    int num = 0;
        //    for (int i = 0; i < memorySpage.Length; i++)
        //    {
        //        num = (num + memorySpage[i]) % 0xffff;
        //    }
        //    return num;
        //    实际上num 这里已经是结果了,如果只是取int 可以直接返回了 
        //    //memorySpage = BitConverter.GetBytes(num);
        //    返回累加校验和 
        //    //return BitConverter.ToInt16(new byte[] { memorySpage[0], memorySpage[1] }, 0);
        //}
        /// <summary>
        /// CRC计算
        /// </summary>
        /// <param name="arr">源数据</param>
        /// <returns></returns>
        public static byte[] Crc(byte[] arr)
        {

            UInt32 i;
            UInt16 j, uwCrcReg = 0xFFFF;

            for (i = 0; i < arr.Length; i++)
            {
                uwCrcReg ^= arr[i];
                for (j = 0; j < 8; j++)
                {
                    if ((uwCrcReg & 0x0001) != 0)
                    {
                        uwCrcReg = (UInt16)((UInt16)(uwCrcReg >> 1) ^ (UInt16)0xA001);
                    }
                    else
                    {
                        uwCrcReg = (UInt16)(uwCrcReg >> 1);
                    }
                }
            }
            byte[] CRC = new byte[2];
            CRC[0] = (byte)(uwCrcReg);
            CRC[1] = (byte)(uwCrcReg >> 8);
            return CRC;
        }

        /// <summary>
        /// 计算和校验
        /// </summary>
        /// <param name="bt">参数集合</param>
        /// <returns></returns>
        public static byte Checksum(byte[] bt)
        {
            //求和
            int ret = 0; ;
            for (int i = 0; i < bt.Length; i++)
                ret = ret + (int)bt[i];

            //ret = (byte)(ret + 0x01);
            return (byte)ret;

        }


        /// <summary>
        /// 取一个数组在另一个数组中的最左侧位置
        /// </summary>
        /// <param name="b"></param>
        /// <param name="bb"></param>
        /// <returns></returns>
        public static int GetByteLeftIndexOf(byte[] b, byte[] bb)
        {
            if (b == null || bb == null || b.Length == 0 || bb.Length == 0 || b.Length < bb.Length)
                return -1;

            int i, j;
            for (i = 0; i < b.Length - bb.Length + 1; i++)
            {
                if (b[i] == bb[0])
                {
                    for (j = 1; j < bb.Length; j++)
                    {
                        if (b[i + j] != bb[j])
                            break;
                    }
                    if (j == bb.Length)
                        return i;
                }
            }
            return -1;
        }

        /// <summary>
        /// 取一个数组在另一个数组中的最右侧位置
        /// </summary>
        /// <param name="b"></param>
        /// <param name="bb"></param>
        /// <returns></returns>
        public static int GetByteRightIndexOf(byte[] b, byte[] bb)
        {
            if (b == null || bb == null || b.Length == 0 || bb.Length == 0 || b.Length < bb.Length)
                return -1;

            int i, j;
            for (i = b.Length - bb.Length; i > -1; i--)
            {
                if (b[i] == bb[0])
                {
                    for (j = 1; j < bb.Length; j++)
                    {
                        if (b[i + j] != bb[j])
                            break;
                    }
                    if (j == bb.Length)
                        return i;
                }
            }
            return -1;
        }

        /// <summary>
        /// 在byte数组中搜索另一个数组的位置
        /// </summary>
        /// <param name="data"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static List<int> ByteIndexOf(byte[] data, byte[] pattern)
        {
            List<int> matchedPos = new List<int>();

            if (data.Length == 0 || data.Length < pattern.Length) return matchedPos;

            int end = data.Length - pattern.Length;
            bool matched = false;

            for (int i = 0; i <= end; i++)
            {
                for (int j = 0; j < pattern.Length || !(matched = (j == pattern.Length)); j++)
                {
                    if (data[i + j] != pattern[j]) break;
                }
                if (matched)
                {
                    matched = false;
                    matchedPos.Add(i);
                }
            }
            return matchedPos;
        }


        /// <summary>
        /// 比较两个字节数组是否相等
        /// </summary>
        /// <param name="b1">byte数组1</param>
        /// <param name="b2">byte数组2</param>
        /// <returns>是否相等</returns>
        public static bool CompareByte(byte[] b1, byte[] b2)
        {
            if (b1.Length != b2.Length) return false;
            if (b1 == null || b2 == null) return false;
            for (int i = 0; i < b1.Length; i++)
                if (b1[i] != b2[i])
                    return false;
            return true;
        }

        /// <summary>
        /// 10进制转换为16进制
        /// </summary>
        /// <param name="hexString">10进制数值</param>
        /// <returns>16进制byte数组</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>
        /// 判断是否十六进制格式字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsHexadecimal(string str)
        {
            const string PATTERN = @"[A-Fa-f0-9]+$";
            bool bo = System.Text.RegularExpressions.Regex.IsMatch(str, PATTERN);

            if (bo == true)
            {
                // 长度判断 长度+1 与3的余数为0表示长度符合要求
                if ((str.Length + 1) % 3 != 0)
                {
                    bo = false;
                }
                else
                {
                    // 空格判断,空格数为长度+1 与3的余数
                    if (str.Length > 2)
                    {

                        string[] arr = str.Split(new char[] { ' ' });

                        //分离后,得到空格数
                        int space_count = arr.Length - 1;

                        //实际空格数
                        int n = ((str.Length + 1) / 3) - 1;

                        // 获得字符串中所有的空格数
                        int cout = Regex.Matches(str, @" ").Count;

                        if (space_count != n || cout != space_count)
                        {
                            bo = false;
                        }
                        else
                        {
                            for (int i = 0; i < str.Length; i++)
                            {
                                if ((i + 1) % 3 == 0)
                                {
                                    // 判断 2 5 8 11 .. 位置是否为空格
                                    if (str[i] != ' ')
                                    {
                                        bo = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    else if (str.Length < 2)
                    {
                        bo = false;
                    }
                }
            }

            return bo;
        }
        /// <summary>
        /// 十六进制换算为十进制
        /// </summary>
        /// <param name="strColorValue"></param>
        /// <returns></returns>
        public static int GetHexadecimalValue(String strColorValue)
        {
            char[] nums = strColorValue.ToCharArray();
            int total = 0;
            try
            {
                for (int i = 0; i < nums.Length; i++)
                {
                    String strNum = nums[i].ToString().ToUpper();
                    switch (strNum)
                    {
                        case "A":
                            strNum = "10";
                            break;
                        case "B":
                            strNum = "11";
                            break;
                        case "C":
                            strNum = "12";
                            break;
                        case "D":
                            strNum = "13";
                            break;
                        case "E":
                            strNum = "14";
                            break;
                        case "F":
                            strNum = "15";
                            break;
                        default:
                            break;
                    }
                    double power = Math.Pow(16, Convert.ToDouble(nums.Length - i - 1));
                    total += Convert.ToInt32(strNum) * Convert.ToInt32(power);

                }

            }
            catch (System.Exception ex)
            {
                String strErorr = ex.ToString();
                return -1;
            }


            return total;
        }
        // <summary>
        /// 把十六进制格式的字符串转换成字节数组。
        /// </summary>
        /// <param name="pString">要转换的十六进制格式的字符串</param>
        /// <returns>返回字节数组。</returns>
        public static byte[] getBytesFromString(string pString)
        {
            string[] str = pString.Split(' ');     //把十六进制格式的字符串按空格转换为字符串数组。
            byte[] bytes = new byte[str.Length];     //定义字节数组并初始化,长度为字符串数组的长度。
            for (int i = 0; i < str.Length; i++)     //遍历字符串数组,把每个字符串转换成字节类型赋值给每个字节变量。
                bytes[i] = Convert.ToByte(Convert.ToInt32(str[i], 16));
            return bytes;     //返回字节数组。
        }

        public static int bytesToInt4(byte[] src, int offset)

        {//src为byte数组,offset从数组的第office位开始
            int value;
            value = (int)((src[offset + 3] & 0xFF)
                | ((src[offset + 2] & 0xFF) << 8)
               | ((src[offset + 1] & 0xFF) << 16)
               | ((src[offset] & 0xFF) << 24)

       );
            return value;
        }

        public static int bytesToInt2(byte[] src, int offset)
        {//src为byte数组,offset从数组的第office位开始
            int value;
            value = (int)(
               ((src[offset] & 0xFF))) | ((src[offset + 1] & 0xFF << 8));
            return value;
        }

        /// <summary>
        /// 16进制原码字符串转字节数组
        /// </summary>
        /// <param name="hexString">"AABBCC"或"AA BB CC"格式的字符串</param>
        /// <returns></returns>
        public static byte[] ConvertHexStringToBytes(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if (hexString.Length % 2 != 0)
            {
                throw new ArgumentException("参数长度不正确");
            }

            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="s"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <param name="fenge">是否每字符用逗号分隔</param>
        /// <returns></returns>
        public static string ToHex(string s, string charset, bool fenge)
        {
            if ((s.Length % 2) != 0)
            {
                s += " ";//空格
                //throw new ArgumentException("s is not valid chinese string!");
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            byte[] bytes = chs.GetBytes(s);
            string str = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
                if (fenge && (i != bytes.Length - 1))
                {
                    str += string.Format("{0}", ",");
                }
            }
            return str.ToLower();
        }

        /**/
        /// <summary>
        /// 从16进制转换成汉字
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static string UnHex(string hex, string charset)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("\n", "");
            hex = hex.Replace("\\", "");
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
            }
            // 需要将 hex 转换成 byte 数组。 
            byte[] bytes = new byte[hex.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。 
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                    System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message. 
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            return chs.GetString(bytes);
        }   

/// <summary>
        /// 根据文件的路径使用文件流打开,并保存为byte[]
        /// </summary>
        /// <param name="imagepath">文件路径</param>
        /// <returns></returns>
        public static byte[] GetByteFromFile(string imagepath)
        {

            try
            {
                FileStream fs = new FileStream(imagepath, FileMode.Open);
                byte[] byData = new byte[fs.Length];
                fs.Read(byData, 0, byData.Length);
                fs.Close();
                return byData;
            }
            catch
            {
                return null;
            }
        }                                                                                                                                      
        /// 读取数据库中文件流转换成文件
        /// </summary>
        /// <param name="filename">存放位置</param>
        /// <param name="b">数据库中存放的文件流</param>
        /// <returns></returns>
        public static bool SaveByteToFile(string filename,Byte[] b)
        {
            try
            {
                FileStream stream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
                if (stream.CanWrite)
                {
                    stream.Write(b, 0, b.Length);
                }

                stream.Close();
                return true;
            }
            catch (Exception )
            {
                //throw e;
                return false;
            }

        }

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落尘521

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值