日期:2014-05-17 浏览次数:21095 次
byte[] myByte1 = new byte[] { 0x04, 0x3f};//字节数组,byte为0-255的类型
             BitArray myBit2 = new BitArray(myByte1);           
             PrintValues(myBit2, 8);
public static void PrintValues(IEnumerable myList, int myWidth) //myWidth指定每行显示的个数
        {
            int i = myWidth;
            string num="";
            foreach (Object obj in myList)  //迭代一列数
            {
                if (i <= 0)
                {
                    i = myWidth;
                }
                i--;
                num += obj.Equals(true) ? ((ulong)1).ToString() : ((ulong)0).ToString();
              
            }
            MessageBox.Show(num);           
        }
        private string GetBitString(byte byteDate)
        {
            string result = string.Empty;
            for (int i = 0; i < 8; i++)
            {
                byte tempDate = (byte)(byteDate & 0x80);
                if (tempDate == 0x80)
                {
                    result += "1";
                }
                else
                {
                    result += "0";
                }
                byteDate <<= 1;
            }
            return result;
        }
------解决方案--------------------
byte[] myByte1 = new byte[] { 0x04, 0x3f, 0x34, 0xd5, 0x6f };
PrintValues(myByte1, 6);
        static void PrintValues(byte[] b, int width)
        {
            StringBuilder strbuilder = new StringBuilder(b.Length * sizeof(byte));
            int len = 0;
            for (int i = 0; i < b.Length; i++)
            {
                for (byte j = 8; j > 0; j--)
                {
                    strbuilder.Append((b[i] & (byte)Math.Pow(2, j - 1)) >> (j - 1));
                    len++;
                    if (len % width == 0)
                        strbuilder.Append('\n');
                }
            }
            MessageBox.Show(strbuilder.ToString());
        }