Elixir - Bitwise Operators



Bitwise operators work on bits and perform bit by bit operation. Elixir provides bitwise modules as part of the package Bitwise, so in order to use these, you need to use the bitwise module. To use it, enter the following comand in your shell −

use Bitwise

Assume A to be 5 and B to be 6 for the following examples −

Operator Description Example
&&& Bitwise and operator copies a bit to result if it exists in both operands. A &&& B will give 4
||| Bitwise or operator copies a bit to result if it exists in either operand. A ||| B will give 7
>>> Bitwise right shift operator shifts first operand bits to the right by the number specified in second operand. A >>> B will give 0
<<< Bitwise left shift operator shifts first operand bits to the left by the number specified in second operand. A <<< B will give 320
^^^ Bitwise XOR operator copies a bit to result only if it is different on both operands. A ^^^ B will give 3
~~~ Unary bitwise not inverts the bits on the given number. ~~~A will give -6

Example

Try the following code to understand all arithmetic operators in Elixir.

a = 5
b = 6

use Bitwise

IO.puts("a &&& b " <> to_string(a &&& b))

IO.puts("a ||| b " <> to_string(a ||| b))

IO.puts("a >>> b " <> to_string(a >>> b))

IO.puts("a <<< b" <> to_string(a <<< b))

IO.puts("a ^^^ b " <> to_string(a ^^^ b))

IO.puts("~~~a " <> to_string(~~~a))

The above program generates the following result −

a &&& b 4
a ||| b 7
a >>> b 0
a <<< b 320
a ^^^ b 3
~~~a -6
elixir_operators.htm
Advertisements