Reputation: 12329
Seems elementary but I am not sure how to get each bit from a byte. Thanks for the help
Upvotes: 1
Views: 572
Reputation: 45119
As RyuuGan already posted you should go with the BitArrary. You just put the data in it by calling the constructor with the wanted elements.
byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 };
BitArray bitArray = new BitArray( myBytes );
Afterwards the instance has some interesting properties to easily access each bit. At first you can just call the index operator to get or set the state of each bit:
bool bit = bitArray[4];
bitArray[2] = true;
Also you can enumerate over all bits by just using a foreach loop (or any LINQ-stuff you like)
foreach (var bit in bitArray.Cast<bool>())
{
Console.Write(bit + " ");
}
To get back from the bits to some specific type (e.g. int) is a little bit trickier, but is quite easy using this extension methods:
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;
}
}
With this in place you can just get out of it with this single line of code:
IList<int> result = bitArray.GetBitsAs<int>();
Upvotes: 2
Reputation: 792
Try to use BitArray.
byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 };
BitArray myBA3 = new BitArray( myBytes );
Upvotes: 2
Reputation: 324790
The bits are "numbered" 0 to 7 from right to left. So to get the 5th bit, you'd use byte & (1<<5)
I'm sure there's a clearer way of explaining this >_>
EDIT: This would work in an IF
statement, but if you want just the 1 or 0 specifically, use winwaed's solution.
Upvotes: 3
Reputation: 7829
Use the bit shift.
Eg. Bit 3: b = (value >> 3) & 1;
The final and masks bit 1. if you want Boolean, just compare (==) the above with the value 1.
Upvotes: 1