Skip to content

Instantly share code, notes, and snippets.

@TG9541
Last active April 25, 2020 10:22
Show Gist options
  • Save TG9541/fb7471701c796d8c68db23c38d642b9a to your computer and use it in GitHub Desktop.
Save TG9541/fb7471701c796d8c68db23c38d642b9a to your computer and use it in GitHub Desktop.
Notes on BF! (version with X as the working register) and BF@ (Little Endian)
; starting from B! ( t a u -- )
; t a u
; 1 $100 7
; bit# Addr Bool
; 00 01 01 00 FF FF
; == --- ===== =====
; 72 1F 01 00 81 FF
; X 1,X 2,X 4,X
; BF! ( t a u -- )
; Write bit to a bitfield stored in one or more cells (16 bit words)
; Set/reset bit #u (0..8191) in a cell array starting at address a to bool t
; Note: creates/executes BSER/BRES + RET code on Data Stack
HEADER BFRSS "BF!"
BFRSS: LDW Y,X ; use X as the working register
LDW X,(X) ; get bit number
LD A,XL
PUSH A ; keep LSB
SRLW X ; divide by 8 to get byte offset
SRLW X
SRLW X
LD A,XL ; deal with STM8 Big Endian
XOR A,#1
LD XL,A ; now the LSB comes first
LDW YTEMP,X ; bit offset
LDW X,Y
LDW X,(2,X)
ADDW X,YTEMP
LDW (2,Y),X ; add bit offset to address
LD A,#0x72 ; Opcode BSET/BRES
LD (Y),A
POP A ; LSB of bit number
AND A,#0x07
SLA A ; n *= 2 -> A
OR A,#0x10
LDW X,Y
LDW X,(4,X) ; bool b (0..15) -> Z
JRNE 1$ ; b!=0: BSET
INC A ; b==0: BRES
1$: LDW X,Y
LD (1,X),A ; 2nd byte of BSET/BRES
LD A,#EXIT_OPC ; Opcode RET
LD (4,X),A
ADDW X,#6
JP (Y)
; BF@ ( a u )
; a u
; $100 7
; bit# Addr
; -- -- 00 07 01 00
; ----- ===== =====
; 72 0E 01 00 00 81
; X2 X1 2,X 4,X
; BF@ ( a u -- b )
; read bit #u (0..8191) in the byte at address
; Note: creates/executes BTJT addr,#bit,0 + RET code on Data Stack
HEADER BFAT "BF@"
BFAT: LDW Y,X ; stack ( a u )
LDW X,(X) ; get bit number
LD A,XL ; keep LSB
SRLW X ; divide by 8 to get byte offset
SRLW X
SRLW X
EXGW X,Y ; Y now offset to address
DECW X
AND A,#0x07 ; LSB of bit number
SLA A ; n *= 2 -> A
LD (X),A ; 2nd byte of BTJT
DECW X
LD A,#0x72 ; Opcode BTJT (or BSET/BRES)
LD (X),A ; stack ( a u BTJT )
EXGW X,Y
LDW YTEMP,X ; X again offset to address
LDW X,Y
LDW X,(4,X) ; get address
ADDW X,YTEMP ; add offset to address
EXGW X,Y
LDW (2,X),Y ; put addr at the right spot for BTJT
CLR A ; dummy relative jump
LD (4,X),A
LD A,#EXIT_OPC ; Opcode RET
LD (5,X),A
CLRW Y
CALL (X) ; BTJT addr,#bit,0 -> bit in C flag
JRNC 1$
CPLW Y
1$: ADDW X,#4 ; 2DROP
LDW (X),Y
RET
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment