-
-
Notifications
You must be signed in to change notification settings - Fork 2
Bitwise operations
Normally, all the math you do in ICE modifies bytes at a time; this makes sense, as each number is represented by one, two, or three bytes. However, there are situations in which you'd want to modify values by one bit at a time. Each byte is made up of 8 bits, each bit is either a 1 or a 0. When a bit is 1, it is considered to be "set", otherwise it is considered to be "reset". The action of changing a bit to it's opposite (changing a 1 to a 0 or a 0 to a 1) is called "flipping". The right-most bit of a byte is bit 0, the one to the left of that is bit 1, to the left of that is bit 2, etc. These situations are where you would want to use bitwise operators. The bitwise operators are plot style tokens, which you access from the bottom of the catalog ([2nd]
, [0]
), below the inequality signs. They look like a miniature plus sign, a square outline, and a dot.
The three tokens are as follows:
Operator | Explanation |
---|---|
EXP1+EXP2 |
Bitwise OR of EXP1 and EXP2. |
EXP1·EXP2 |
Bitwise AND of EXP1 and EXP2. |
EXP1□EXP2 |
Bitwise XOR of EXP1 and EXP2. |
In the terminology we just gave you: bitwise OR is used to set bit(s), bitwise AND is used to reset bit(s), bitwise XOR is used to flip bit(s).
They look like this in the catalog:
If you're already familiar with binary or you read the previous subsection, you know that each bit in binary data is a power of two. The right-most bit is 2^0 = 1
, the bit left of that 2^1 = 2
, left once more is 2^2 = 4
, etc. This is important to know for bitwise operators, because you need to know what the values you are using look like in binary. Say for example that you wanted to flip bit 4 of the three byte value, 4233, which looks like this: 000000000001000010001001
. Because we want to flip bit 4 of 4233, we must use the bitwise XOR operator with two to the power of 4, which looks like this: 4233□16→A
.
We used 16 after the bitwise XOR because 2^4 = 16
. The result of the A in the example is 4249, which looks like this: 000000000001000010011001
. It may not be very apparent right now, but bitwise operators are more useful when you’re dealing with memory and pointers.
ICE Compiler | Peter Tillema
- Introduction
- Building your first program
- Math and numbers
- Variables
- Standard system commands
- Program flow control
- Pointers
- Graphics
- Sprites
- Tilemaps
- Useful routines