Author |
Message |
- Joined: 05 Sep 2013
- Posts: 3828
- Location: Stockholm, Sweden
|
swap two bits in a byte
Posted: Fri Mar 13, 2020 11:13 am
|
a question for the ASM black belts in here:
how would you swap position of two bits in a byte quickly without using a LUT?
I mean, say I want %abcdefgh to become %abgdefch
if it's easier, I may settle for a solution that works only if the two bits are adjacent, as in %abcedfgh
|
|
|
- Joined: 05 Sep 2013
- Posts: 3828
- Location: Stockholm, Sweden
|
Posted: Fri Mar 13, 2020 11:24 am
|
replying myself - I probably have an idea that involves testing the two bits and a XOR operation to be possibly performed
will leave this open for now ;)
|
|
|
- Site Admin
- Joined: 19 Oct 1999
- Posts: 14745
- Location: London
|
Posted: Fri Mar 13, 2020 11:34 am
|
Untested...
; test value is in b, bitmask for the bits in question in c
; return in a
ld a,b
and c
jr z, +
cp c
jr z, +
ld a,b
xor c ; we are flipping the bits
ret
+:
; the bits are identical
ld a,b
ret
The idea is that if the bits are the same, there's nothing to do, else you want to XOR them with the bitmask. If they can't be the same, or the bitmask is constant, there may be some possibility to optimise.
|
|
|
- Joined: 05 Sep 2013
- Posts: 3828
- Location: Stockholm, Sweden
|
Posted: Fri Mar 13, 2020 11:44 am
|
yeah, I had the very same idea, but then I thought we can actually do the two separate test as one
; test value is in b, bitmask for the bits in question in c
; return in a
ld a,b
and c
ld a,b ; this doesn't affect flags
jp pe,+ ; check if Parity is EVEN
xor c ; if not, we are flipping the bits
+:
ret
|
|
|
- Site Admin
- Joined: 19 Oct 1999
- Posts: 14745
- Location: London
|
Posted: Fri Mar 13, 2020 11:46 am
|
Ah, that’s a good one... the parity flag is so rarely useful that I forgot it :)
I think you can ret pe to save a bit more time and space.
|
|
|
- Joined: 05 Sep 2013
- Posts: 3828
- Location: Stockholm, Sweden
|
Posted: Fri Mar 13, 2020 11:54 am
|
improved version. Thanks Maxim - I had forgot about the conditional RET
; test value is in b, bitmask for the bits in question in c
; return in a
ld a,b
and c
ld a,b ; this doesn't affect flags
ret pe ; if Parity Flag is EVEN we don't need any flip
xor c ; if not, we are flipping the bits
ret
|
|
|