Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set each bit in a byte array

Tags:

arrays

c#

How do I set each bit in the following byte array which has 21 bytes or 168 bits to either zero or one?

byte[] logonHours

Thank you very much

like image 830
KSM Avatar asked Feb 07 '26 15:02

KSM


2 Answers

Well, to clear every bit to zero you can just use Array.Clear:

Array.Clear(logonHours, 0, logonHours.Length);

Setting each bit is slightly harder:

for (int i = 0; i < logonHours.Length; i++)
{
    logonHours[i] = 0xff;
}

If you find yourself filling an array often, you could write an extension method:

public static void FillArray<T>(this T[] array, T value)
{
    // TODO: Validation
    for (int i = 0; i < array.Length; i++)
    {
        array[i] = value;
    }
}
like image 191
Jon Skeet Avatar answered Feb 09 '26 04:02

Jon Skeet


BitArray.SetAll:

System.Collections.BitArray a = new System.Collections.BitArray(logonHours);
a.SetAll(true);

Note that this copies the data from the byte array. It's not just a wrapper around it.

like image 22
noobish Avatar answered Feb 09 '26 05:02

noobish