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
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
Share Improve this question edited Sep 19, 2017 at 14:51 asked Sep 19, 2017 at 14:39 user6691398user6691398 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? – Sebastian Simon Commented Sep 19, 2017 at 14:41
-
myInt & 8
?... – Matt Burland Commented Sep 19, 2017 at 14:41 - please be more specific about whetrher the bit is still in same position – px1mp Commented Sep 19, 2017 at 14:41
- 2 stackoverflow./questions/1436438/… – jftuga Commented Sep 19, 2017 at 14:42
- Maybe this will help: stackoverflow./a/1436448/4673847 – Roy Berris Commented Sep 19, 2017 at 14:42
3 Answers
Reset to default 6myInt = 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
I think you can use the bitwise AND
https://developer.mozilla/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
}
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)));
}