summaryrefslogtreecommitdiff
path: root/Optimizing-assembly-code.md
diff options
context:
space:
mode:
authorRangi <remy.oukaour+rangi42@gmail.com>2020-11-25 12:27:32 -0500
committerRangi <remy.oukaour+rangi42@gmail.com>2020-11-25 12:58:23 -0500
commit844036cf125c7d44aa1cc80a5056b763b6eb54d5 (patch)
treeffa63f3caab3dc52272fa73507707a4e0795a970 /Optimizing-assembly-code.md
parent750ed9aeeb9897adbf0b993da8ff02f57efa5e28 (diff)
http://www.retroprogramming.com/2014/01/fast-z80-bit-reversal.html
Diffstat (limited to 'Optimizing-assembly-code.md')
-rw-r--r--Optimizing-assembly-code.md51
1 files changed, 51 insertions, 0 deletions
diff --git a/Optimizing-assembly-code.md b/Optimizing-assembly-code.md
index bc5c107..b3453b4 100644
--- a/Optimizing-assembly-code.md
+++ b/Optimizing-assembly-code.md
@@ -22,6 +22,7 @@ WikiTI's advice fully applies here:
- [Increment or decrement `a`](#increment-or-decrement-a)
- [Invert the bits of `a`](#invert-the-bits-of-a)
- [Rotate the bits of `a`](#rotate-the-bits-of-a)
+ - [Reverse the bits of `a`](#reverse-the-bits-of-a)
- [Set `a` to some constant minus `a`](#set-a-to-some-constant-minus-a)
- [Set `a` to one constant or another depending on the carry flag](#set-a-to-one-constant-or-another-depending-on-the-carry-flag)
- [Increment or decrement `a` when the carry flag is set](#increment-or-decrement-a-when-the-carry-flag-is-set)
@@ -172,6 +173,56 @@ But do:
The exception is if you need to set the zero flag when the operation results in 0 for `a`; the two-byte operations can set `z`, the one-byte operations cannot.
+### Reverse the bits of `a`
+
+(This optimization is from [Retro Programming](http://www.retroprogramming.com/2014/01/fast-z80-bit-reversal.html)).
+
+Don't do:
+
+```asm
+; 10 bytes, 59 cycles
+ ld bc, 8 ; lb bc, 0, 8
+.loop
+ rra
+ rl b
+ dec c
+ jr nz, .loop
+ ld a, b
+```
+
+And don't do:
+
+```asm
+; 27 bytes, 27 cycles
+ ld b, 0
+rept 8
+ rra
+ rl b
+endr
+ ld a, b
+```
+
+But do:
+
+```asm
+; 17 bytes, 17 cycles
+ ld b, a
+ rlca
+ rlca
+ xor b
+ and $aa
+ xor b
+ ld b, a
+ rlca
+ rlca
+ rlca
+ rrc b
+ xor b
+ and $66
+ xor b
+```
+
+
### Set `a` to some constant minus `a`
Don't do: