如何检查一个字节的位[]

时间:2014-08-29 03:14:29

标签: c# bytearray

我从字节[]数据中得到一个Base64编码的字符串,我必须检查其中的位。

当我得到" AAAB"时,我将其解码为byte [],并且当A = {000000}且B = {000001}时,我得到[{00000000} {00000000} {00000001} ]

问题是我想要计算哪一口是1.在上面的情况中,1的位是数字24,所以我想得到24。

这就是我想要做的事情:

使用SCOTT提出的解决方案进行编辑:

using using System.Linq;

string stringData = "AAAB"; // {000000} {000000} {000000} {000001}
byte[] byteData = Convert.FromBase64String(stringData); // {00000000}{00000000}{00000001}
BitArray bitData = new BitArray(byteData.Reverse().ToArray()); // {100000000000000000000000}

 var i = bitData .Length;
 foreach (bool bit in bitData )
                        {
   if (bit)
   {
     //display i, the bit 1
   }
   j--;
 }

非常感谢,Scott!

3 个答案:

答案 0 :(得分:2)

处理此问题的最简单方法是将byte[]转换为BitArray

string stringData = "AAAB"; // {000000} {000000} {000000} {000001}
byte[] byteData = Convert.FromBase64String(stringData); // {00000000}{00000000}{00000001}

BitArray bitData = new BitArray(byteData.Reverse().ToArray()); // {000000000000000000000001}


Console.WriteLine("byteData");
for(var i=0; i < byteData.Length; i++){ //bitData.Length is 32
    var bitValue = byteData[i];
    Console.WriteLine("{0} {1}", i, bitValue);
}

Console.WriteLine();
Console.WriteLine("bitData");
for(var i=0; i < bitData.Length; i++){ //bitData.Length is 32
    var bitValue = bitData[i];
    Console.WriteLine("{0} {1}", i, bitValue);
}

Run this example

重要提示,i将从最低有效位(当前为1)开始计数,然后向右移动。因此,您的输出将为true, false, ..., false, false而不是false, false ..., false, true。如果你想要它,那么在.Reverse().ToArray()上抛出另一个bitData

Console.WriteLine();
Console.WriteLine("reversed");
var reversed = bitData.Cast<bool>().Reverse().ToArray();
for(var i=0; i < reversed.Length; i++){ //bitData.Length is 32
    var bitValue = reversed[i];
    Console.WriteLine("{0} {1}", i, bitValue);
}

答案 1 :(得分:1)

我曾写过Extension Method以允许在一个字节内获取和设置单个位;也许这会对你有帮助。

public static class MyExtensions
{
    /// <summary>
    /// Sets an individual bit inside a byte, based on the bit number.
    /// </summary>
    /// <param name="aByte">The byte where a bit is to be changed.</param>
    /// <param name="bitNumber">The bit number to read (between 0 and 7).</param>
    /// <param name="value">The value to set the bit to.  0/False or 1/True.</param>
    /// <returns>A byte with the requested bit changed.</returns>
    /// <remarks>The bit number must be between 0 and 7, otherwise an ArgumentOutOfRangeException is thrown.</remarks>
    public static byte SetBit(this byte aByte, byte bitNumber, bool value)
    {
        if (bitNumber > 7) { throw new ArgumentOutOfRangeException("bitNumber", "bitNumber was > 7"); }

        // create a mask of zeros except for the bit we want to modify
        byte mask = 1;
        mask = (byte)(mask << bitNumber);

        if (value)
        {
            // use bitwise-inclusive-or operator to make sure the bit equals 1 (and nothing else is changed)
            aByte = (byte)(aByte | mask);
        }
        else
        {
            // grab the inverse of our original mask (all ones except our bit equals zero)
            mask = (byte)(byte.MaxValue - mask);

            // use bitwise-and operator to make sure our bit equals 0 (and nothing else is changed)
            aByte = (byte)(aByte & mask);
        }
        return aByte;
    }


    /// <summary>
    /// Returns the value of an individual bit from within a byte.
    /// </summary>
    /// <param name="aByte">The byte from which to return bit data.</param>
    /// <param name="bitNumber">The bit number to read (between 0 and 7).</param>
    /// <returns>The value inside the requested bit.  0/False or 1/True.</returns>
    /// <remarks>The bit number must be between 0 and 7, otherwise an ArgumentOutOfRangeException is thrown.</remarks>
    public static bool GetBit(this byte aByte, byte bitNumber)
    {
        if (bitNumber > 7) { throw new ArgumentOutOfRangeException("bitNumber", "bitNumber was > 7"); }

        // create a mask of zeros except for the bit we want to modify
        byte mask = 1;
        mask = (byte)(mask << bitNumber);

        // use bitwise-and operator with our mask; if we get a 1, our bit must have also been a 1
        return (aByte & mask) > 0;
    }

}   

使用:

        byte b = 128;
        b = b.SetBit(1, true);

        bool b0 = b.GetBit(0); // false
        bool b1 = b.GetBit(1); // true, because we set it
        bool b2 = b.GetBit(2); // false
        bool b3 = b.GetBit(3); // false
        bool b4 = b.GetBit(4); // false
        bool b5 = b.GetBit(5); // false
        bool b6 = b.GetBit(6); // false
        bool b7 = b.GetBit(7); // true, because we started with 128

答案 2 :(得分:0)

希望这有帮助。

        string stringData = "AAAB"; 
        byte[] byteData = Convert.FromBase64String(stringData); 
        StringBuilder sb = new StringBuilder("{");

        BitArray ba = new BitArray(byteData);
        for (int i = 0; i < ba.Length; i++)
        {
            sb.Append(ba[i] ? "1" : "0");    //append 1 if true, 0 if false.

            if (((i + 1) % 8 == 0) && ((i + 1) < ba.Length))  //adds formatting
                sb.Append("}{");
        }

        sb.Append("}");
        Console.Write("Bytes:" + sb.ToString());
        Console.Read(); //pause