Set Specific Bit in Byte Array

Nevets picture Nevets · Jan 28, 2014 · Viewed 30.5k times · Source

I want to know how to set a specific bit in a 16 byte array (128 bits).

For example ... if I wanted to set the 9th bit in the the array I would expect:

{00, 80, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00}

If I wanted to set the 125th bit ...

{00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 08}

I have looked into using bit shifting but got confused on how to bit shift with an array consisting of 128 bits. Is there a way to break down an array this size and evaluate in smaller chunks of bytes? Any help would be appreciated.

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Jan 28, 2014

The process of selecting a specific bit consists of two steps:

  • Picking the byte, and then
  • Picking the bit.

Picking the byte is simple: all you need to do is dividing the bit index by the number of bits in a byte - i.e. dividing by eight:

int byteIndex = bitIndex / 8;

Now that you know what byte to use, calculate which bit you want to access. For that you need to compute a remainder of a division by eight, like this:

int bitInByteIndex = bitIndex % 8;

With these two indexes in hand, it is easy to access the bit: use 1 << bitInByteIndex as a mask, like this:

byte mask = (byte)(1 << bitInByteIndex);
bool isSet = (bytes[byteIndex] & mask) != 0;
// set to 1
bytes[byteIndex] |= mask;
// Set to zero
bytes[byteIndex] &= ~mask;
// Toggle
bytes[byteIndex] ^= mask;