ds1709
ds1709

Reputation: 199

Modify specific bit in byte

I need to modify (!not toggle XOR!) specific bit in byte value. I have:

  1. source byte (e.g. b11010010);
  2. index of bit to modify (e.g. 4);
  3. new value of bit (0 or 1).

Now, what I need. If new value is 0, then bit[4] must be set to 0. If new value is 1, then bit[4] must be set to 1.

General part:

var bitIndex = 4;
var byte = b11010010;
var mask = 1 << bitIndex;
var newValue = 1;

This is the easiest way to do this:

if(newValue == 1)
    byte |= mask; // set bit[bitIndex]
else
    byte &= ~mask; // drop bit[bitIndex]

Another way allows to do this without if else statement, but look to hard to understand:

byte = byte & ~mask | (newValue << bitIndex) & mask

Here, first AND drops bit[bitIndex], second AND calculates new value for bit[bitIndex], and OR set bit[bitIndex] to calculated value, not matter is it 0 or 1.

Is there any easier way to set specific bit into given value?

Upvotes: 5

Views: 5814

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283614

(newValue << bitIndex) only has a single bit set, there's no need for & mask.

So you have just 5 operations.

byte = byte & ~(1 << bitIndex) | (newValue << bitIndex); // bitIndex'th bit becomes newValue

It's still complex enough to be worth a comment, but easy to see that the comment is correct because it's two easily recognized operations chained together (unlike the current accepted answer, which requires every reader to sit down and think about it for a minute)

Upvotes: 3

TomServo
TomServo

Reputation: 7409

The canonical way to do this is:

byte ^= (-newValue ^ byte) & (1 << n);

Bit number n will be set if newValue == 1, and cleared if newValue == 0

Upvotes: 5

Related Questions