当前位置:编程学习 > C#/ASP.NET >>

如何把位数组转换成字节

如何把位数组转换成字节
如:
byte[]   myBytes   =   new   byte[5]   {   1,   2,   3,   4,   5   }; 
BitArray   myBA3   =   new   BitArray(myBytes); 
已经位数组myBA3 中存储的是位值,如何把位数组myBA3 再转换回字节呢? --------------------编程问答--------------------

int len = myBA3.Length / 8;
byte[] ba = new byte[len];
myBA3.CopyTo(ba, 0);
--------------------编程问答-------------------- #region 十六进制字符串转字节数组
        /// <summary>
        /// 十六进制字符串转字节数组
        /// </summary>
        /// <param name="sHexString">十六进制字符串(AB 01 0A 05 07 09)</param>
        private byte[] ByteArraysFromHexString(string sHexString)
        {
            byte[] cBytes = new byte[0];
            try
            {
                if (sHexString.Length <= 0) return cBytes;

                string[] sHexArr = sHexString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                cBytes = new byte[sHexArr.Length];

                for (int i = 0; i < sHexArr.Length; i++)
                {
                    cBytes[i] = Convert.ToByte(sHexArr[i], 16);
                }

                return cBytes;
            }
            catch
            {
                return cBytes;
            }
        }
        #endregion


        #region 字节数组转十六进制字符串
        /// <summary>
        /// 字节数组转十六进制字符串
        /// </summary>
        /// <param name="cBytes">字节数组</param>
        /// <returns>AB 01 0A 05 07 09</returns>
        private string ByteArraysToHexString(byte[] cBytes)
        {
            try
            {
                if (cBytes.Length <= 0) return "";

                string sHex = "", sHexString = "";
                for (int i = 0; i < cBytes.Length; i++)
                {
                    sHex = "00" + Convert.ToString(cBytes[i], 16);
                    sHex = sHex.Substring(sHex.Length - 2);
                    sHexString = sHexString + sHex.ToUpper() + " ";
                }
                if (sHexString.Length > 0)
                {
                    sHexString = sHexString.Substring(0, sHexString.Length - 1);
                }

                return sHexString;
            }
            catch
            {
                return "";
            }
        }
        #endregion --------------------编程问答-------------------- up --------------------编程问答-------------------- 1 楼是正确的 --------------------编程问答-------------------- 1楼简单点,二楼也忒复杂了吧 --------------------编程问答-------------------- 1   楼是正确
补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,