2

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

6
  • 1
    Why don’t you think this is the best way of doing it? How would you imagine a better approach to look like? Commented Sep 19, 2017 at 14:41
  • myInt & 8?... Commented Sep 19, 2017 at 14:41
  • please be more specific about whetrher the bit is still in same position Commented Sep 19, 2017 at 14:41
  • 2
    stackoverflow.com/questions/1436438/… Commented Sep 19, 2017 at 14:42
  • Maybe this will help: stackoverflow.com/a/1436448/4673847 Commented Sep 19, 2017 at 14:42

3 Answers 3

6
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

Sign up to request clarification or add additional context in comments.

1 Comment

Instead of 0x1 we can use 0b1 as a binary literal
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
}

Comments

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)));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.