Bitwise Operations
Jump to navigation
Jump to search
Bitwise Operations exist in programming languages as a direct way to modify the binary values, or bits, in a number. Sometimes, it's more efficient or useful to modify the bits of a number rather than performing arithmetic on the number. One example of this is a bitmask where you use the BAND operation to choose several bits to check and ignore the others.
Pico8 has a collection of useful bitwise operations: Keep in mind that, since update 0.2.0 when they were added, the operator forms of the bitwise functions run faster in the simulated CPU than the API Calls do.
| Operation Name | API Call | Operator | Description |
|---|---|---|---|
| Bitwise Not | BNOT(A) | ~ A | Inverts all of the bits of the number. 0 swaps to 1 and 1 swaps to 0. (Invert) |
| Bitwise And | BAND(A,B) | A & B | Compares the numbers at each bit position. If the bits are both 1, the result is 1, otherwise if a 1 is compared to a 0, the 0 replaces it.. (Zero-dominant) |
| Bitwise Or | BOR(A,B) | A | B | Compares the numbers at each bit position. If the bits are both 0, the result is 0, but if a 0 is compared to a 1, the 1 replaces it. (One-dominant) |
| Bitwise Exclusive Or | BXOR(A,B) | A ^^ B | Compares the numbers at each bit position. If the bits are the same, the result for that position is a 0, but if a 0 is compared to a 1, the bit is "Exclusively" in only one input, and the result is a 1. (There can be Exclusively One) |
| Arithmetic Shift Left | SHL(A,B) | A << B | Shifts each bit of a number left by B positions. |
| Arithmetic Shift Right | SHR(A,B) | A >> B | Shifts each bit of a number right by B positions. Arithmetic shift attempts to preserve the sign (Positive or negative) of the number by copying the sign bit (farthest left) into the resulting empty positions. |
| Logical Shift Right | LSHR(A,B) | A >>> B | Shifts each bit of a number right by B positions. Logical shift ignores the sign of a number, filling zeroes into the space left over by the shift. |
| Rotate Left | ROTL(A,B) | A <<> B | Rotates each bit of a number left by B positions. In a rotation, bits which "fall off" on the left-hand side are wrapped around to the right of the number. |
| Rotate Right | ROTR(A,B) | A >>< B | Rotates each bit of a number right by B positions. In the rotation, bits which "fall off" on the right-hand side are wrapped around to the left of the number. |