Prev: AE17 Up: Map Next: AE71
AE56: Calculate Square Root
Used by the routine at Position_Rope_End.
Calculates the square root of a 16-bit number, rounded down. It works eight times through, taking two bits of the number each time.
Input
HL Number
Output
L Square root (H is not meaningful)
Calculate_Square_Root AE56 LD DE,$0040 Set up the trial value: D builds up the root and E is 40.
AE59 LD A,L Copy the low byte of the number to A.
AE5A LD L,H Copy the high byte of the number to L.
AE5B LD H,D Clear H.
AE5C LD B,$08 Set a counter in B for eight bits of the root.
AE5E OR A Clear the carry flag.
Calculate_Square_Root_Loop AE5F SBC HL,DE Subtract the trial value (the root so far and 40) from the remainder.
AE61 JR NC,Calculate_Square_Root_Fitted Jump to Calculate_Square_Root_Fitted if it fitted.
AE63 ADD HL,DE Otherwise restore the remainder.
Calculate_Square_Root_Fitted AE64 CCF Invert the carry flag, so that it is set if the trial value fitted.
AE65 RL D Shift the new bit into the root.
AE67 ADD A,A Shift the next bit of the number out of A.
AE68 ADC HL,HL Shift it into the remainder.
AE6A ADD A,A Shift the next bit of the number out of A.
AE6B ADC HL,HL Shift it into the remainder.
AE6D DJNZ Calculate_Square_Root_Loop Decrease the bit counter and loop back until all eight bits of the root have been found.
AE6F LD L,D Copy the root to L.
AE70 RET Return.
Prev: AE17 Up: Map Next: AE71