Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to set/unset an individual bit

Right now I'm using this to set/unset individual bits in a byte:

if (bit4Set)
   nbyte |= (1 << 4);
else
   nbyte &= ~(1 << 4);

But, can't you do that in a more simple/elegant way? Like setting or unsetting the bit in a single operation?

Note: I understand I can just write a function to do that, I'm just wondering if I won't be reinventing the wheel.

like image 519
djeidot Avatar asked Aug 06 '10 12:08

djeidot


People also ask

How do I unset a specific bit?

Use the bitwise AND operator (&) to clear a bit. number &= ~(1 << x); That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.

How do you set a bit in a byte?

Setting a bitUse the bitwise OR operator ( | ) to set a bit. number |= 1UL << n; That will set the n th bit of number . n should be zero, if you want to set the 1 st bit and so on upto n-1 , if you want to set the n th bit.

Which logic operation is used for setting a bit without modifying other bits?

For example, this is necessary to change settings in the microcontroller or other devices. We use bitwise operators to change certain bits while not affecting others.


4 Answers

Sure! It would be more obvious if you expanded the |= and &= in your code, but you can write:

nbyte = (nbyte & ~(1<<4)) | (bit4Set<<4);

Note that bit4Set must be zero or one —not any nonzero value— for this to work.

like image 146
Pascal Cuoq Avatar answered Oct 03 '22 23:10

Pascal Cuoq


Put it in a function, the bool type will enforce 0,1 for all bitval inputs.

int change_bit(int val, int num, bool bitval)
{
    return (val & ~(1<<num)) | (bitval << num);
}
like image 31
Nordic Mainframe Avatar answered Oct 04 '22 00:10

Nordic Mainframe


This is a perfectly sensible and completely standard idiom.

like image 8
Alexandre C. Avatar answered Oct 04 '22 00:10

Alexandre C.


Have you considered assigning mnemonics and/or identifiers to your bits, rather than referring to them by number?

As an example, let's say setting bit 4 initiates a nuclear reactor SCRAM. Instead of referring to it as "bit 4" we'll call it INITIATE_SCRAM. Here's how the code for this might look:

int const INITIATE_SCRAM = 0x10; // 1 << 4

...

if (initiateScram) {
    nbyte |= INITIATE_SCRAM;
} else {
    nbyte &= ~INITIATE_SCRAM;
}

This won't necessarily be any more efficient (after optimization) than your original code, but it's a little clearer, I think, and probably more maintainable.

like image 5
Dan Moulding Avatar answered Oct 03 '22 22:10

Dan Moulding