Advanced concepts
Bitwise operations
hex = 0x12400; bin = 0b10011010; b_or = hex | bin ^ hex & bin;
- There are constant formats and bitwise operations for dealing with integers on the bit level.
- The following integer constant formats are available:
- Binary (base 2): begins with "0b", followed by some binary digits (0,1)
- Octal (base 8): begins with "0o", followed by some octal digits (0-7)
- Decimal (base 10): contains only decimal digits (0-9)
- Hexadecimal (base 16): begins with "0x", followed by some hexadecimal digits (0-9,a-f,A-F)
- These operators are available for doing bitwise operations:
- binary AND / AND-assign:
&, &=
- returns 1 if both sides are 1 - binary OR / OR-assign:
|, |=
- returns 1 if any side is 1 - binary XOR / XOR-assign:
^, ^=
- returns 1 if either side is 1, but not both - unary NOT:
~
- inverts bits - left shift / left shift-assign:
<<, <<=
- move all bits to the left (more significant positions) - right shift / right shift-assign:
>>, >>=
- move all bits to the right (less significant positions)
- binary AND / AND-assign:
The main difference from other languages is that the integer type by default is 64 bits long. Left/right shift rules are equal to those of the C language. Thus, it is safe to use only shift distances between 0 and 63.
Truth tables for AND/OR/XOR operations
AND | 0 | 1 | OR | 0 | 1 | XOR | 0 | 1 | ||
---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | ||
1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 |