How do I check if a value is a positive or negative number in JavaScript using bitwise operations?
Richard W
richard w profile pic

In JavaScript, you can use bitwise operations to check if a value is a positive or negative number. The most common bitwise operation used for this purpose is the sign bit check using the bitwise AND operator (&). Here's how you can do it: To check if a value is a positive number, you can perform a bitwise AND operation with the value and0x80000000, which is the sign bit for 32-bit signed integers. If the result is0, it indicates that the value is positive.

1
2
3
4

function isPositive(value) {
  return (value & 0x80000000) === 0;
}

To check if a value is a negative number, you can perform the same bitwise AND operation but with a different value. In this case, you need to check if the sign bit is set to1.

1
2
3
4

function isNegative(value) {
  return (value & 0x80000000) !== 0;
}

Here's an example usage:

1
2
3
4
5
6
7
8

console.log(isPositive(10));    // true
console.log(isPositive(-5));    // false
console.log(isPositive(0));     // true (considered positive)

console.log(isNegative(-10));   // true
console.log(isNegative(5));     // false
console.log(isNegative(0));     // false (considered positive)

Note that bitwise operations in JavaScript implicitly convert the operands to signed 32-bit integers. So, if you're working with numbers greater than 32 bits or floating-point numbers, the bitwise operations may not produce accurate results. It's important to mention that using bitwise operations for checking positive or negative numbers is not the most common or recommended approach in JavaScript. The>,<,>=,<=, or=== operators are generally more readable and suitable for these comparisons in most cases.