2010-11-15 67 views

回答

2

由於RyuuGan已經發布,你應該去與BitArrary。您只需通過調用帶有所需元素的構造函數將數據放入其中即可。

byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 }; 
BitArray bitArray = new BitArray(myBytes); 

之後,該實例有一些有趣的屬性可以輕鬆訪問每一位。首先,你可以只調用索引操作者獲取或設置每個位的狀態:

bool bit = bitArray[4]; 
bitArray[2] = true; 

您也可以通過只使用一個foreach循環枚舉所有位(或任何你喜歡的LINQ的東西)

foreach (var bit in bitArray.Cast<bool>()) 
{ 
    Console.Write(bit + " "); 
} 

要想從比特到某些特定類型(如int),背面是有點麻煩,但很容易使用這個擴展方法:

public static class Extensions 
{ 
    public static IList<TResult> GetBitsAs<TResult>(this BitArray bits) where TResult : struct 
    { 
     return GetBitsAs<TResult>(bits, 0); 
    } 

    /// <summary> 
    /// Gets the bits from an BitArray as an IList combined to the given type. 
    /// </summary> 
    /// <typeparam name="TResult">The type of the result.</typeparam> 
    /// <param name="bits">An array of bit values, which are represented as Booleans.</param> 
    /// <param name="index">The zero-based index in array at which copying begins.</param> 
    /// <returns>An read-only IList containing all bits combined to the given type.</returns> 
    public static IList<TResult> GetBitsAs<TResult>(this BitArray bits, int index) where TResult : struct 
    { 
     var instance = default(TResult); 
     var type = instance.GetType(); 
     int sizeOfType = Marshal.SizeOf(type); 

     int arraySize = (int)Math.Ceiling(((bits.Count - index)/8.0)/sizeOfType); 
     var array = new TResult[arraySize]; 

     bits.CopyTo(array, index); 

     return array; 
    } 
} 

有了這個地方,你可以乾脆退出的它用這一行代碼:

IList<int> result = bitArray.GetBitsAs<int>(); 
1

使用

Convert.ToString (value, 2) 
1

使用移位。

例如,位3:b =(值>> 3)& 1;

最終和麪具位1 如果你想布爾,只是比較(==)以上,其值爲1

+1

位3被零引用。 IE瀏覽器。最低值位爲0.對於一個字節,最高值爲7 – winwaed 2010-11-15 03:11:55

3

的位由右至左「編號爲」 0〜7。因此,要獲得第5位,你會使用byte & (1<<5)
我敢肯定有解釋的更清楚的方式該> _>

編輯:這將在IF聲明中工作,但如果你只想要1 0具體來說,使用winwaed的解決方案。

2

嘗試使用BitArray

byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 }; 
BitArray myBA3 = new BitArray(myBytes);