If I had to set 4th bit,
Which is the best way
Method 1: a |= (1 << 3)
Method 2: a |= 8
Please elaborate the difference.
If I had to set 4th bit,
Which is the best way
Method 1: a |= (1 << 3)
Method 2: a |= 8
Please elaborate the difference.
These two are equivalent.
Using 1 << 3
is more clear to the reader which bit you want to set. And because this expression is a compile-time constant, compilers will typically calculate the value at compile time so there is no run-time overhead.
As you noticed, both of these do the same thing. Let me focus on the part which is different:
As you can see, the result is the same binary number: 0000 1000
If I have to choose between these 2, I'd pick the shift, as this is more obvious that you want a bit. However, personally, I would pick a third variant when creating these numbers: 0b0000'1000
The 0b
stands for binary literal, available since C++14 and the '
is a digit separator (also C++14), which is similar to the spaces I used earlier.
However, to be fair, I think you are using the wrong tool for the job assuming a
is an integer. std::bitset
is created to do these kind of bit manipulations. (Even available in C++98)
#include <bitset>
#include <iostream>
int main(int, char**)
{
auto a = std::bitset<8>{};
a.set(3 /*zero based indexing*/);
std::cout << a.to_string() << std::endl;
return 0;
}
The output of the program: 00001000
As you can see, you can very easy set bits with the method set
as if it was any other container. See documentation for more things you can do.