Operators and bit manipulation
!!! warning This auditors' handbook is frozen and obsolete; the Nim language manual alongside other Nim documentation, Status Nim style guide, Chronos guides, and Nim by Example supercede it.
Operators
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
In-particular:
- bitwise and, or, flip, xor are denoted
and
,or
,not
,xor
instead of using a symbol - shift left and right are
shl
andshr
- division and modulo are
div
andmod
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:
https://nim-lang.org/docs/manual.html#syntax-precedence
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
https://github.com/status-im/nim-stew/blob/master/stew/bitops2.nim