# Add two binary numbers together # Written December, 1998 by pete gammie <> peteg at unsw dot edu dot au # Use (m)ark symbols to remember what the current digit is # (c)one represents a carry, and the current digit is 1 tape alphabet is blank, zero, one, mzero, mone, cone, equals; # Add the numbers 9 (1001) and 14 (1110) = 23 (10111) # Initialise tape to "1001 1110=" print "one"; move right one square; print "zero"; move right one square; print "zero"; move right one square; print "one"; move right one square; print "blank"; move right one square; print "one"; move right one square; print "one"; move right one square; print "one"; move right one square; print "zero"; move right one square; print "equals"; # Position tape head on the last digit of the first number rewind: if the tape symbol is "blank" then go to rewindf; move left one square; go to rewind; rewindf: move left one square; # Flag this digit as current if the tape symbol is "zero" then { print "mzero"; go to getdigit; }; if the tape symbol is "one" then { print "mone"; go to getdigit; }; # first number is empty ??? # Move to the end of the second number getdigit: if the tape symbol is "equals" then go to getdigitf; move right one square; go to getdigit; getdigitf: print "blank"; move left one square; # Pick up the digit if the tape symbol is "zero" then { print "equals"; go to addzero; }; if the tape symbol is "one" then { print "equals"; go to addone; }; # second number exhausted; patch up the result patch: if the tape symbol is "cone" then go to patchco; if the tape symbol is "mone" then go to patchmo; if the tape symbol is "mzero" then go to patchmz; move left one square; go to patch; patchco: print "zero"; move left one square; print "one"; go to halt; patchmo: print "one"; go to halt; patchmz: print "blank"; go to halt; # Add zero to the current digit addzero: if the tape symbol is "cone" then go to fazco; if the tape symbol is "mone" then go to fazmo; if the tape symbol is "mzero" then go to fazmz; move left one square; go to addzero; fazco: print "zero"; go to carry; fazmo: print "one"; go to nextdigit; fazmz: print "zero"; go to nextdigit; # Add one to the current digit addone: if the tape symbol is "cone" then go to faoco; if the tape symbol is "mone" then go to faomo; if the tape symbol is "mzero" then go to faomz; move left one square; go to addone; faoco: print "one"; go to carry; faomo: print "zero"; # Handle a carry carry: move left one square; if the tape symbol is "blank" then { print "one"; go to nextdigita; }; if the tape symbol is "zero" then { print "one"; go to nextdigita; }; print "cone"; go to getdigit; faomz: print "one"; # Handle no carry nextdigit: move left one square; nextdigita: if the tape symbol is "blank" then { print "mzero"; go to getdigit; }; if the tape symbol is "zero" then { print "mzero"; go to getdigit; }; print "mone"; go to getdigit; halt: .