JavaScript - bitwise NOT operator
The main goal of this article is to show how bitwise NOT operation (~
operator) works on the JavaScript example.
The main concept of the bitwise NOT operation is to change each bit to oposite bit.
Bitwise example:
0101
NOT ----
1010 <---- bitwise NOT operation result
Hint: 0101 in base 10 has 5 value
The truth table for the NOT operation is:
a | NOT a (in JavaScript: ~a ) | JS Example |
0 | 1 | ~0 |
1 | 0 | ~1 |
So, the above table on 1 bit numbers can be presented in JavaScript as:
// ONLINE-RUNNER:browser;
console.log(getBits(~0, 1)); // 1
console.log(getBits(~1, 1)); // 0
// Helpers:
function getBits(number, length) {
let text = '';
for (let i = length - 1; i > -1; --i) {
text += 0x01 & (number >> i);
}
return text;
}
More complex eample
JavaScript uses Two's complement to store numbers in the operating memory.
It means:
- if the number is positive, in base 2 has filling with
0
numbers on the left, - if the number is negative, in base 2 has filling with
1
numbers on the left.
Hint: check this article to know how Two's complement works.
// ONLINE-RUNNER:browser;
const a = 5; // 00000101
console.log(a); // 5 (in dec / base 10, number with Two's complement)
console.log(getBits(a, 8)); // 00000101 (in bin / base 2)
const result = ~a; // <----- bitwise NOT operation example
console.log(result); // -6 (in dec / base 10, number with Two's complement)
console.log(getBits(result, 8)); // 11111010 (in bin / base 2)
// ^^^^^
// | |
// filling with 1 (-6 is a negative number)
// Helpers:
function getBits(number, length) {
let text = '';
for (let i = length - 1; i > -1; --i) {
text += 0x01 & (number >> i);
}
return text;
}
Bitwise NOT operation limitations
Hint: in JavaScript, bitwise NOT works on 32-bit integers. If number is bigger, the most significant bits are dicarded to get 32-bit integer number - it means only bits indexed from 0 to 31 will be used.
So, the above table can be also written as:
5 (base 10) = 00000000000000000000000000000101 (base 2)
--------------------------------
~5 (base 10) = 11111111111111111111111111111010 (base 2) = -6 (base 10, 32 bit number with Two's complement)
Features
1. bitwise NOT operation is fast - easy to do by any CPU.