Files
R8Forge/drv/divmod_signed.r8asm
T
dsh 1f3f453e88 signed: the two two's complement wrappers, with exhaustive sweeps
clb_digits_signed N REG S T F prints '-' (45) and then |N| as the same four
zero padded digits; clb_divmod_signed N D Q R S T1 T2 F is the C style
truncated division (q = trunc(n/d), r = n - q*d, remainder follows the
dividend).  Both are wrappers: clb_digits / clb_divmod still do the work, so
the tape only grows by the sign handling -- 572 characters for the display
(12151 vs 11579 in the same driver layout) and 1191 for the division
(6018 vs 4827).

The sign bit is read with rol + bit_copy + ror, 49 characters.  clb_bit_mov is
deliberately NOT used: it eats the source bit, so N comes back as N - HALF and
1024 -- whose magnitude 1024 only fits the unsigned range -- prints as 0000.
A clb_sub_nc against a HALF constant was the other candidate: 765 characters
for the call plus ~60 for the constant cell.

A flag has to outlive the block that consumes it, because biz/rnz only exit
once the body clears the condition bit.  So sign(N) is moved into T2, sign(D)
into F, and the remainder block flips F into sign(N)^sign(D) on its way out;
a single conditional negation of the quotient then carries the xor.  The
negation scratch is S+6: the only cell in S with a "clean on entry" contract,
and clb_neg_ip leaves it zero again for clb_divmod.

Verified by r8forge_byte_op_test: all 2048 values for the display (worst
117606 steps) and 4202 division pairs -- every |a|,|b| <= 32 plus the
0/+-1/+-1023/+-1024 boundary combinations -- compared against C's / and %.
examples/signed_demo.r8asm is the single point regression that runs as a
program (the flagship cannot carry them: +12.1k / +5.6k on a 62351 tape).
2026-11-18 21:13:52 +08:00

24 lines
685 B
Plaintext

%include "asm/divmod.r8asm"
; clb_divmod_signed 的驱动:0 号 cell 放被除数、1 号放除数,输出商和余数。
;
; r8forge_derive drv/divmod_signed.r8asm -2 0=7 1=2 # 3 1
; r8forge_derive drv/divmod_signed.r8asm -2 0=2040 1=2 # 2044 2040? 不,
; r8forge_derive drv/divmod_signed.r8asm -2 0=(2048-7) 1=2 # -3 -1 = 2045 2047
;
; out 依次是商、余数(二补码,所以 2045 就是 -3)。N、D 被吃成绝对值(加 -2 能看到),
; T1、T2 和 F 结束时都是 0。全扫在 r8forge_byte_op_test 里。
.var N 0
.var D 1
.var Q 2
.var R 3
.var S 5
.var T1 12
.var T2 13
.var F 14
clb_divmod_signed N D Q R S T1 T2 F
output Q
output R