I have a simple question – I need to write a function for my program to change the 3rd bit of a given byte.
I wrote those lines :
public byte turnOn(Byte value)
{
int flag = 8;
value = (byte) (value | flag);
return value;
}
I’m not sure if it’s the right way to do that, because I saw also this way (with which I am unfamiliar)
value = (byte) (value | (1 << 2) );
which way is better, and what does 1 << 2 means (2 means the third bit, but what is the 1 )
Thanks!
1 << 2means 1 shifted two bits to the left. Since shifting left by one bit is similar to multiplying by two, this gives 4. In binary, this isi.e. the 3rd bit from the right is set.
The constant
1is used since that number only has a single bit set – the rightmost bit. After shifting left, only the 3rd bit (from the right) is set:I prefer using
1 << 2instead of a constant like8, as it makes it clearer which bit is being set. It also prevents you inadvertently using a constant that has multiple bits set – unless you actually want that, of course. Even then, it’s clearer in my opinion to add together several bits, for clarity: