Operators and bit manipulation


A set of symbol and keywords can be used as infix operators Nim supports operator overloading.

Those symbols are:

=     +     -     *     /     <     >
@     $     ~     &     %     |
!     ?     ^     .     :     \

The keyword operators are

and or not xor shl shr div mod in notin is isnot of as


  • bitwise and, or, flip, xor are denoted and, or, not, xor instead of using a symbol
  • shift left and right are shl and shr
  • division and modulo are div and mod

Implementation-defined behaviors

mod is defined as the mathematical remainder, like C. With signed integers a mod b has the same sign as a

shr of a signed integer will not preserve the sign bit. ashr can be used for arithmetic right shift.

This distinction was introduced recently and may lead to subtle bugs, also ashr relies on the C compiler actually lowering >> to SAR for signed integer. This is specified for GCC and Clang (https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation) but implementation defined in general.

Operator precedence

Operator precedence is specified described in the manual:


Additional system operators

Nim system exports additional operators with a % like +% and -%. Those cast the signed integer operand to unsigned and cast the result back to signed. This is intended to use with the ByteAddress type for pointer arithmetic

Bit manipulation