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.
First you need to find out which byte you're working with. Let's say you have:
00000000 00000000 00000000 00000000 ...
And you want to turn on the 10th bit, so it needs to become like this:
00000000 01000000 00000000 00000000 ...
So first do a division by 8 (rounded down) to locate the byte number (in this case byte number one, or the second byte). Once you've done that, you can use bitwise operators to set the bit you want, i.e.
array[1] |= 0x40
We're doing a bitwise OR operation between the old value of that byte and 0x40 (which is 01000000
). If the old value was 00101101
, then array[1]
= (00101101 OR 01000000)
, which is 01101101
.
Naturally, in this case I've been using literals so you'll have to change that depending on which bit is set (e.g. if you're setting the bit before the last, you want to use 0x02
instead, etc.
You could use a BitArray:
byte[] bytearray = new byte[16];
var bitArray = new BitArray(bytearray);
bitArray.Set(8, true);
bitArray.CopyTo(bytearray, 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With