Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Specific Bit in Byte Array

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.

like image 604
Nevets Avatar asked Jan 28 '14 14:01

Nevets


2 Answers

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.

like image 155
Gigi Avatar answered Sep 21 '22 15:09

Gigi


You could use a BitArray:

byte[] bytearray = new byte[16];

var bitArray = new BitArray(bytearray);

bitArray.Set(8, true);

bitArray.CopyTo(bytearray, 0);
like image 22
Håkan Fahlstedt Avatar answered Sep 18 '22 15:09

Håkan Fahlstedt