Skip to content

Instantly share code, notes, and snippets.

@eievui5
Created September 8, 2021 17:41
Show Gist options
  • Save eievui5/8b316b385b731c346ed9d28b658588e7 to your computer and use it in GitHub Desktop.
Save eievui5/8b316b385b731c346ed9d28b658588e7 to your computer and use it in GitHub Desktop.
Used to address large arrays of boolean values, packing 8 values into each byte.
; Bitfield Library, by Eievui
; Used to address large arrays of boolean values, packing 8 values into each
; byte.
; Set Nth bool:
; ld a, N
; call GetBitfieldMask
; or a, [hl]
; ld [hl], a
; Reset Nth bool:
; ld a, N
; call GetBitfieldMask
; cpl
; and a, [hl]
; ld [hl], a
; Get Nth bool:
; ld a, N
; call GetBitfieldMask
; and a, [hl]
; Flip Nth bool:
; ld a, N
; call GetBitfieldMask
; xor a, [hl]
; ld [hl], a
SECTION "Address Bitfield", ROM0
; Returns the mask of the input flag, and the address in `hl`
; This can be used to `and a, [hl]` or `or a, [hl] \ ld [hl], a`
; @ input:
; @ b: Flag index
; @ hl: Bitfield Array
; @ output:
; @ a: Flag mask
; @ hl: Flag address
GetBitfieldMask::
; Get the address containing the target bit.
ld a, b
and a, %11111000
rra ; `and` always resets carry flag.
rra
rra
; add hl, a
add a, l
ld l, a
adc a, h
sub a, l
ld h, a
; Get the proper bitmask Using the lower 3 bits.
ld a, b
and a, %00000111
ASSERT @ == GetBitA, "This function uses a fallthrough to GetBitA."
; Returns the mask of the input value
; @ input:
; @ a: Value
; @ output:
; @ a: Mask
GetBitA::
; `a = 1 << a`. Used for indexing into bitfields.
; Thanks, calc84maniac.
; Check if resulting bit should be in high or low nibble
sub a, 4
jr nc, .highNibble
; Convert 0 -> $01, 1 -> $02, 2 -> $04, 3 -> $05
add a, 2
adc a, 3
jr .fixupResult
.highNibble
; Convert 4 -> $10, 5 -> $20, 6 -> $40, 7 -> $50
add a, -2
adc a, 3
swap a
.fixupResult
; If result was $05/$50, convert to $08/$80
add a, a
daa
rra
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment