Powered by AppSignal & Oban Pro

Bitwise

elixir_livebooks/bitwise.livemd

Bitwise

Section

A set of functions that perform calculations on bits.

All bitwise functions work only on integers; otherwise an ArithmeticError is raised.

The functions in this module come in two flavors: named or operators. For example:

use Bitwise
# named
bnot(1)
# operator
1 &&& 1

If you prefer to use only operators or skip them, you can pass the following options:

  • :only_operators - includes only operators
  • :skip_operators - skips operators

For example:

use Bitwise, only_operators: true
1 &&& 1

When invoked with no options, use Bitwise is equivalent to import Bitwise.

All bitwise functions can be used in guards:

odd? = fn
  int when Bitwise.band(int, 1) == 1 -> true
  _ -> false
end

odd?.(1)

All functions in this module are inlined by the compiler.

Function &&&/2

Bitwise AND operator.

Calculates the bitwise AND of its arguments.

Allowed in guard tests. Inlined by the compiler.

Examples

9 &&& 3

Function <<>>/2

Arithmetic right bitshift operator.

Calculates the result of an arithmetic right bitshift.

Allowed in guard tests. Inlined by the compiler.

Examples

1 >>> 2
1 >>> -2
-1 >>> 2
-1 >>> -2

Function band/2

Calculates the bitwise AND of its arguments.

Allowed in guard tests. Inlined by the compiler.

Examples

band(9, 3)

Function bnot/1

Calculates the bitwise NOT of the argument.

Allowed in guard tests. Inlined by the compiler.

Examples

bnot(2)
bnot(2) &amp;&amp;&amp; 3

Function bor/2

Calculates the bitwise OR of its arguments.

Allowed in guard tests. Inlined by the compiler.

Examples

bor(9, 3)

Function bsl/2

Calculates the result of an arithmetic left bitshift.

Allowed in guard tests. Inlined by the compiler.

Examples

bsl(1, 2)
bsl(1, -2)
bsl(-1, 2)
bsl(-1, -2)

Function bsr/2

Calculates the result of an arithmetic right bitshift.

Allowed in guard tests. Inlined by the compiler.

Examples

bsr(1, 2)
bsr(1, -2)
bsr(-1, 2)
bsr(-1, -2)

Function bxor/2

Calculates the bitwise XOR of its arguments.

Allowed in guard tests. Inlined by the compiler.

Examples

bxor(9, 3)

Function |||/2

Bitwise OR operator.

Calculates the bitwise OR of its arguments.

Allowed in guard tests. Inlined by the compiler.

Examples

9 ||| 3

Function ~~~/1

Bitwise NOT unary operator.

Calculates the bitwise NOT of the argument.

Allowed in guard tests. Inlined by the compiler.

Examples

~~~2
~~~2 &amp;&amp;&amp; 3