Search code examples
javascriptbitboolean-logicboolean-operations

What is the correct way to set bit in bitmask?


I'm little bit confuced about a proper way to set bits in bitmask. I have the following function and flags:

var userBmask = 0;

const EMAIL_CONFIRMED = 1;
const EMAIL_UNSUBSCRIBED = 2; 

setBit: function (bit) {
    userBmask |= 1 << bit; // 10
}

Let's say I want to set bit for email confirmation:

setBit(EMAIL_CONFIRMED);

After the line above my userBmask is: 10. But I'm not sure this is correct because actualy I set second bit instead first. Should I rewrite setBit function to the folowing to set bits from most right bit?:

setBit: function (bit) {
    userBmask |= 1 << bit - 1; // 01
}

Now after setBit(EMAIL_CONFIRMED) I get result 01

EDIT: Thanks for your answers. Please look at the following. Becase I'm using javascript that is 32bit I can have bitmask with `0...31 bits. But if I try to set the last available bit (with is 31) I get negative number:

const NEXT_BIT = 31; 

setBit(NEXT_BIT); // userBmask now is -10000000000000000000000000000000

Is it expected behavior and could be result of possible bugs?


Solution

  • I think you are assuming that the lowest value bit is "bit one", this is actually not correct.

    Consider "powers of two" which is the basis of binary numbers...

    2^0 == 1 //first bit is "bit zero" 
    2^1 == 2 //second bit is "bit one"
    2^2 == 4 //third bit is "bit two"
    2^3 == 8 //fourth bit is "bit three"
    //and so on
    

    If you shift 1 left by 1 then you go from 2^0 to 2^1. So binary 10 is decimal 2.

    If you want to set the lowest bit in userBmask when you pass 1 to your function then yes you'll have to subtract 1 from bit before you do the shift.