# HG changeset patch # User Steve Losh # Date 1482083725 18000 # Node ID 64e956e4603b860ea48982561ff9e4ed3ba0fc9f # Parent 58287c034c3c2c5552fafa4d29c15fa6fea9d08d Clean up the BCD stuff diff -r 58287c034c3c -r 64e956e4603b content/blog/2016/12/chip8-cpu.markdown --- a/content/blog/2016/12/chip8-cpu.markdown Sat Dec 17 23:00:51 2016 -0500 +++ b/content/blog/2016/12/chip8-cpu.markdown Sun Dec 18 12:55:25 2016 -0500 @@ -931,41 +931,48 @@ We'll split this into two parts to make it easier to read. First we'll make -a `bcd` function to actually get the digits: +a `digit` function to retrieve a digit of a number: ```lisp -(defun-inline bcd (integer) - (values (-<> integer (floor <> 100) (mod <> 10)) - (-<> integer (floor <> 10) (mod <> 10)) - (-<> integer (floor <> 1) (mod <> 10)))) - +(defun-inline digit (position integer &optional (base 10)) + (-<> integer + (floor <> (expt base position)) + (mod <> base))) ``` -And make sure it works on its own: +We could have hard-coded the base 10, but part of the Common Lisp tradition is +making flexible functions that can be reused in the future when it's not much +harder to do so. + +Let's make sure it works on its own: + +```lisp +(digit 0 135) +1 -``` -[SBCL] CHIP8> (bcd 135) +(digit 1 135) +3 + +(digit 2 135) +5 -1 -3 -5 +(digit 0 #xD6 16) +6 + +(digit 1 #xD6 16) +13 ; 13 in base 10 == D in base 16 ``` And then we can define the actual operation: ```lisp (define-instruction op-ld-bcd