-1

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.

SRIKANTH
  • 65
  • 7
  • 3
    There is no difference at execution time. Any compiler should constant-fold `1 << 3` into `8`. At *reading* time the difference is that `1 << 3` makes it clear that you're setting the third bit. – user207421 Nov 10 '19 at 04:22

2 Answers2

2

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

As you noticed, both of these do the same thing. Let me focus on the part which is different:

  • (1 << 3) take the number 1 (binary: 0000 0001) and shift it 3 spots to the left (binary: 0000 1000)
  • 8 take the number 8 (binary: 0000 1000)

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

Code at Compiler Explorer

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.

JVApen
  • 11,008
  • 5
  • 31
  • 67