Bitwise operators

Operator

Syntax

Computes on the bits of whole numbers: && and, || or, ~~ exclusive or, ! flips every bit, << and >> shift.

<a> && <b>
<a> || <b>
<a> ~~ <b>
!<a>
<a> << <n>
<a> >> <n>

Also written : &&, ||, ~~, !, <<, >>

Parts

<a>A number, worked on as a signed 32-bit integer. Decimals are dropped: 3.7 || 0 is 3.
<b>A number, worked on as a signed 32-bit integer.
<n>The number of bit positions to shift. >> keeps the sign: -16 >> 2 is -4.

Good to know

  • The symbols are bitwise and the words are logical. && is not AND, and || is not OR. This is the reverse of C and JavaScript.
  • A bit test needs parentheses: && comes after =, so flags && 4 = 4 means flags && (4 = 4). Write (flags && 4) = 4, or simply IF flags && 4 THEN.
  • Results are signed 32-bit: 1 << 31 is -2147483648, and !5 is -6.
  • XOR does not exist: it compiles, but the program does not start. Write ~~.
  • A single & is not string concatenation: "a" & "b" gives 0. Join strings with +.
  • Inside a #IF condition, &&, || and ! are the logical words, not these operators.
  • Binary literals are written %1010, hexadecimal 0xFF. Flags from ENUMERATIONBINARY combine with ||.

Example

flags = %1100Console(Str(flags && %1010))   ' 8Console(Str(flags || %0011))   ' 15Console(Str(flags ~~ %1010))   ' 6Console(Str(!0))   ' -1Console(Str(1 << 4))   ' 16Console(Str(-16 >> 2))   ' -4IF (flags && 4) = 4 THEN Console("bit set")   ' bit set
In the manual : Constants and operators