1

I have an integer and i want to check if a single bit is 0 or 1.

What is the best practise for doing that?

An example of what i'm doing at this moment:

const myInt = 8; // Binary in 32 Bit integer = 00000000000000000000000000001000
const myBit = myInt << 28 >>> 31; // 00000000000000000000000000000001

if (myBit === 1) {
    //do something
}

But i think that this isn't the best methode for doing this.

Have you any better idea?

EDIT: It is always the same bit i want to check, but the integer is different

3 Answers3

3
myInt = 8+4; // 1100
n = 3;
(myInt >> n) & 0x1; //  1
n = 2;
(myInt >> n) & 0x1; //  1
n = 1;
(myInt >> n) & 0x1; //  0
n = 0;
(myInt >> n) & 0x1; //  0

general solution shifts your number by N bits to right, and applies bitmask, that leaves only last bit, all other are set to 0

Nikita
  • 163
  • 2
  • 9
0

I think you can use the bitwise AND

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators

my32Bit = 123414123;
twoBy7 = 128;

//check the 7th bit
if (my32Bit & twoBy7) {
  // should return 1 if the 7thbit is 1
}
AndreaBogazzi
  • 14,323
  • 3
  • 38
  • 63
0

You could take the bit and a left shift << with bitwise AND & operator.

var value = 10,
    bit;
    
for (bit = 0; bit < 4; bit++) {
    console.log(bit, !!(value & (1 << bit)));
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392