Binary bitwise operators in JavaScript
This blog post describes JavaScript’s binary bitwise operators: bitwise And (&), bitwise Or (|), and bitwise Xor (^).
In the following examples, we work with binary numbers, via the following two operations:
num.toString(2) converts the number num to a string in binary notation. For example:
Bitwise And: number1 & number2
Bitwise Or: number1 | number2
Bitwise Xor (eXclusive Or): number1 ^ number2
There are two ways to intuitively understand binary bitwise operators.
The operator ^^ does not exist. If it did, it would work like this (the result is true if exactly one of the operands is true):
These operators work with 32-bit integers. That is, they convert their operands to 32-bit integers and produce a result that is a 32-bit integer (encoded as a floating point number, at least externally).
Inputting and outputting binary numbers
In the following examples, we work with binary numbers, via the following two operations:
parseInt(str, 2) parses a string str in binary notation (base 2). For example:
> parseInt('110', 2)
6
num.toString(2) converts the number num to a string in binary notation. For example:
> 6..toString(2)
'110'
Binary bitwise operators
Bitwise And: number1 & number2
> (parseInt('11001010', 2) & parseInt('1111', 2)).toString(2)
'1010'
Bitwise Or: number1 | number2
> (parseInt('11001010', 2) | parseInt('1111', 2)).toString(2)
'11001111'
Bitwise Xor (eXclusive Or): number1 ^ number2
> (parseInt('11001010', 2) ^ parseInt('1111', 2)).toString(2)
'11000101'
There are two ways to intuitively understand binary bitwise operators.
First explanation: one boolean operation per bit. In the formulas below, ni means bit i of number n interpreted as a boolean (0 is false, 1 is true). For example, 20 is false, 21 is true.
- And: resulti = number1i && number2i
- Or: resulti = number1i || number2i
- Xor: resulti = number1i ^^ number2i
The operator ^^ does not exist. If it did, it would work like this (the result is true if exactly one of the operands is true):
x ^^ y === (x && !y) || (!x && y)
Second explanation: changing bits of number1 via number2.
- And: keeps only those bits of number1 that are set in number2. This operation is also called masking, with number2 being the mask.
- Or: sets all bits of number1 that are set in number2 and keeps all other bits unchanged.
- Xor: inverts all bits of number1 that are set in number2 and keeps all other bits unchanged.
Comments
Post a Comment