[2014-01-27] bitwise_ops, numbers, dev, javascript, jsint, jslang

(Ad, please don’t block)

This blog post describes JavaScript’s binary bitwise operators: bitwise And (`&`), bitwise Or (`|`), and bitwise Xor (`^`).
## Inputting and outputting binary numbers

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:
## Binary bitwise operators

Bitwise And: `number1 & number2`
`number1 | number2`
`number1 ^ number2`
`^^` does not exist. If it did, it would work like this (the result is `true` if exactly one of the operands is `true`):
## Further reading

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).

`parseInt(str, 2)` parses a string `str` in binary notation (base 2). For example:

> parseInt('110', 2) 6

> 6..toString(2) '110'

> (parseInt('11001010', 2) & parseInt('1111', 2)).toString(2) '1010'Bitwise Or:

> (parseInt('11001010', 2) | parseInt('1111', 2)).toString(2) '11001111'Bitwise Xor (eXclusive Or):

> (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, `n _{i}` means bit

- And:
`result`_{i}= number1_{i}&& number2_{i} - Or:
`result`_{i}= number1_{i}|| number2_{i} - Xor:
`result`_{i}= number1_{i}^^ number2_{i}

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.