Bitwise operators allow you to manipulate individual bits within integer values. These are essential for low-level programming, flags, and certain mathematical optimizations.
DWScript provides three shift operators.
| Operator | Name | Description |
|---|---|---|
shl |
Shift Left | Shifts bits to the left, filling with zeros. Equivalent to multiplying by $2^n$. |
shr |
Logical Shift Right | Shifts bits to the right, filling with zeros. |
sar |
Arithmetic Shift Right | Shifts bits to the right, preserving the sign bit (MSB). |
When shifting a negative number (where the high bit is 1), shr will fill the high bit with 0 (making it positive), while sar will fill it with 1 (maintaining the negative sign).
var val := -8;
PrintLn(val shr 1);
PrintLn(val sar 1); 9223372036854775804 -4
When applied to integers, standard logical operators perform bitwise operations.
| Operator | Operation |
|---|---|
and |
Bitwise AND |
or |
Bitwise OR |
xor |
Bitwise XOR |
not |
Bitwise NOT (One's complement) |
const FLAG_READ = %0001;
const FLAG_WRITE = %0010;
const FLAG_EXEC = %0100;
var myFlags := FLAG_READ or FLAG_EXEC; // Combine flags
// Check if a flag is set
if (myFlags and FLAG_READ) <> 0 then
PrintLn('Can Read');
// Toggle a flag
myFlags := myFlags xor FLAG_EXEC;
PrintLn(myFlags); Can Read 1
To make bitwise operations more readable, you can use binary and hexadecimal literals.
% (e.g., %101010)$ (e.g., $FF00)var b := %1111; // 15
var h := $A; // 10
PrintLn(b and h); 10