Checking Odd or Even
In this approach, we are using bitwise AND (&) to check the least significant bit of n. If it’s set (odd), “odd” is printed; otherwise, “even” is printed.
Syntax:
if (num & 1) {
// num is odd
} else {
// num is even
}
Example: In this example, we are using the above-explained approach.
Javascript
let n = 8; if (n & 1) { console.log(n + " is odd." ); } else { console.log(n + " is even." ); }; |
Output
8 is even.
Bit manipulation in JavaScript
Bit manipulation in JavaScript refers to the manipulation and operation of individual bits within binary representations of numbers and JavaScript uses 32-bit signed integers for numeric values. It involves using bitwise operators (&, |, ^, ~, <<, >>) to manipulate individual bits of binary numbers. These operations can be used for bitwise logic operations such as AND, OR, XOR, and shifting bits.
Below is a list of bitwise operators:
- Bitwise AND(&): Returns true if both operands are true.
- Bitwise OR(|): Returns true even if one operand is true.
- Bitwise XOR(^): Returns true if both operands are different.
- Bitwise NOT(~): Flips the value of the operand.
- Bitwise Left Shift(<<): Shifts the bit toward the left.
- Bitwise Right Shift(>>): Shifts the bit towards the right.
- Zero Fill Right Shift(>>>): Shifts the bit towards the right but adds 0 from the left.
Below we will describe the common bit manipulation problems in detail:
Table of Content
- Checking Odd or Even
- Swap Two Numbers
- Finding the Single Odd Occurrence
- Power of Two Checks
- Count Total Bits Set
Contact Us