Arithmetic Primitives (Binary)

These arithmetic primitives are for serial (one bit wide) logic and use registers (environment variables) A (the accumulator), B (the other number), and CF (carry) and BF (borrow) flags. In all the arithmetic functions, the result is left in the accumulator, overflow goes into CF, underflow goes into BF, and the variable 'x' is used to hold intermediate results.

My intent is to eventually develop a reasonably complete set of serial ALU functions, but don't hold your breath waiting for the rest of the functions.

The first function I'll develop is the simple ADD function. This version is a strict development from the logic primatives on the Logic page. It is not optimum.


 :add
 if %AX% == 0 if %BX% == 0 if %CF% == 0 set x=00
 if %AX% == 0 if %BX% == 0 if %CF% == 1 set x=01
 if %AX% == 0 if %BX% == 1 if %CF% == 0 set x=01
 if %AX% == 0 if %BX% == 1 if %CF% == 1 set x=10

 if %AX% == 1 if %BX% == 0 if %CF% == 0 set x=01
 if %AX% == 1 if %BX% == 0 if %CF% == 1 set x=01
 if %AX% == 1 if %BX% == 1 if %CF% == 0 set x=10
 if %AX% == 1 if %BX% == 1 if %CF% == 1 set x=11

 if %x% == 00 set AX=0
 if %x% == 00 set CF=0

 if %x% == 01 set AX=1
 if %x% == 01 set CF=0

 if %x% == 10 set AX=0
 if %x% == 10 set CF=1

 if %x% == 11 set AX=1
 if %x% == 11 set CF=1

A slightly different version, one that concatenates the inputs and compares them en masse, simplifies the code somewhat:


 :add
 if %AX%%BX%%CF% == 000 set x=00
 if %AX%%BX%%CF% == 001 set x=01
 if %AX%%BX%%CF% == 010 set x=01
 if %AX%%BX%%CF% == 011 set x=10

 if %AX%%BX%%CF% == 100 set x=01
 if %AX%%BX%%CF% == 101 set x=01
 if %AX%%BX%%CF% == 110 set x=10
 if %AX%%BX%%CF% == 111 set x=11

 if %x% == 00 set AX=0
 if %x% == 00 set CF=0

 if %x% == 01 set AX=1
 if %x% == 01 set CF=0

 if %x% == 10 set AX=0
 if %x% == 10 set CF=1

 if %x% == 11 set AX=1
 if %x% == 11 set CF=1
but also reduces clarity by creating a forest of '%' characters.

If we ignore the logic, and consider the patterns, we can build something like this


 :add
 set x=0
 for %%a in (%AX% %BX% %CX%) do if %%a == 1 set x=%x%%%a

 if %x% == 0    set AX=0
 if %x% == 0    set CF=0

 if %x% == 01   set AX=1
 if %x% == 01   set CF=0

 if %x% == 011  set AX=0
 if %x% == 011  set CF=1

 if %x% == 0111 set AX=1
 if %x% == 0111 set CF=1
which relies on the observation that the result is the binary representation of the number of ones involved (where CF becomes the MSB and AX the LSB). This approach uses rather fewer disk accesses, and is therefore faster than either of the above.

To be continued

  ** Copyright 1995, Ted Davis - all rights reserved ** 

Input and feedback from readers are welcome. NOTE: the subject of the message must contain the word "batch" for the message to get past the spam filter.

Back to the Table of Contents page

Back to my personal links page - back to my home page