ZX Format #07: Efficient Assembler Calculations

Fast calculations in assembler

music by COOPER
(C) GreenFort

Yes, how many problems with this mathematics, and it is necessary, and it is simply needed everywhere. Sometimes vector graphics make themselves known, sometimes counting points in your game, and sometimes calculating the position of celestial bodies in the sky. One way or another, there are always situations when the speed of a ROM calculator is clearly insufficient. We present to your attention a series of articles dedicated to mathematical operations. It is assumed that the person reading these lines has already mastered the basics of programming in Assembler.

Let's start with the simple:

1. DIVISION.

The principle of the division procedure is based on long division, the only difference being the numeral system: it is binary.

1.1 Example of the simplest division procedure:

INPUT: C = Dividend, B = Divisor
OUTPUT: L = result, A = remainder

;L=C/B:
DIVIS XOR A ;reset current remainder
DIVIS2 LD L,#01 ;counter (shift 8 times)
D1 RL C ;read current digit
RLA ;accumulator of digits
CP B ;what is the result of the current digit
JR C,ZER ;jump if current digit=0
SUB B ;current digit=1, subtract from accumulator
SLI L ;store digit=1
JR NC,D1 ;jump if counter did not overflow
RET ;exit
ZER SLA L ;store digit=0
JR NC,D1 ;jump if counter did not overflow
RET ;exit

L - used as a counter and stores the result.
A - remainder of the division, digits are read sequentially from C into register A.
B - remains unchanged after division.

By the way, the procedure can be expanded.

If you need greater precision in division, you can continue dividing.

Example:
LD C,what you will divide
LD B,what you will divide by

CALL DIVIS;initial division
;C=0,A-remainder
LD H,L ;saving the result
CALL DIVIS2 ;secondary division
;without resetting the remainder

Result in HL:

H = integer part of the result
L = fractional part of the result

Achievable precision: +-(1/256), i.e. two decimal places are ensured.

1.2 Procedure for dividing 3-byte numbers

Input: A,H,L - three bytes of the dividend
B,D,E - three bytes of the divisor
Output: A,H,L - result

;A,H,L=(A,H,L)/(B,D,E)
DIVISIO
LD C,A ;store the most significant byte of the dividend in C
XOR A ;reset accumulator
EXX ;digits
LD HL,#01 ;counter (for 24) and
LD B,H ;three-byte holder
EXX ;of the result
DIV1SLA L ;sampling digit
RL H
RL C
RLA
CP B ;is the accumulator greater than the divisor?
JR C,DIV2 ;if less, then result 0)
JR NZ,DIV3; if greater ;result=1, accumulator decreases
EX AF,AF' ;save A
LD A,C ;similarly check
CP D ;the least two bytes of the accumulator and divisor
JR C,DIV22;
JR NZ,DIV32
LD A,H
CP E
JR C,DIV22
DIV32 EX AF,AF' ;accumulator=divisor
DIV3EX AF,AF'
LD A,L ;accumulator-divisor
LD L,H ;(least 2 digits)
LD H,C
AND A
SBC HL,DE
LD C,H
LD H,L
LD L,A
JR NC,DIV33
EX AF,AF' ;accumulator-divisor
SUB B ;most significant digit when
DEC A ;overflow of least
DIV34 EXX ;store in result
SLI L ;current bit=1
RL H
RL B
EXX
JP NC,DIV1;counter still not finished
JP DIVEXIT;counter overflowed ;end of division
DIV22 EX AF,AF' ;store in result=0
DIV2EXX
SLA L
RL H
RL B
EXX
JP NC,DIV1;counter still not finished
DIVEXIT EXX ;counter overflowed
PUSH HL ;end of division
LD A,B
EXX
POP HL
RET
DIV33 EX AF,AF' ;accumulator-divisor
SUB B ;most significant digit without
JP DIV34 ;overflow of least

Then it is quite convenient to use the result for addition or subtraction:

Adding the result to a 3-byte number

CALL DIVISIO
LD B,1st byte to add
LD DE,2nd and 3rd bytes to add
ADD HL,DE
ADC A,B

2. MULTIPLICATION.

Multiplication, like division, is based on long multiplication.

2.1 The simplest multiplication procedure.

Example:

;HL=B*C
LD HL,#0 ;prepare result
LD E,B ;coefficient of current digit
LD D,H
LD B,#08 ;counter
MCYCSRL C ;sampling digit of the second multiplier
JP NC,NOADD ;digit=0 (DE*0=0)
ADD HL,DE ;digit=1 (DE*1=DE)
NOADD SLA E ;change coefficient of digit to the next digit
RL D ;digit to the next digit
DJNZ MCYC ;loop for 8
RET ;exit

Of course, it is immediately noticeable that this construction can also be expanded.

2.2 Multiplication of 3-byte numbers.

;A,H,L=A,H,L*B,D,E

MULTI EXX
LD HL,FLAG;reset carry
RES 0,(HL)
LD B,24 ;counter
LD HL,#0 ;result (C,H,L)
LD C,H
PF2 EXX
SRL B ;sampling digit
RR D ;second multiplier
RR E
JR NC,PF3 ;digit=0, jump to sampling next digit
EX AF,AF' ;addition of answer with
PUSH HL ;current coefficient digit
EXX
POP DE
ADD HL,DE
ADC A,C
JP NC,NOFLAG
;result does not fit in three bytes!
LD A,(FLAG) ;overflow handler
OR 1 ;ni
LD (FLAG),A
RET
NOFLAG LD C,A
EXX
EX AF,AF'
-PF3 SLA L ;jump to the next
RL H ;current coefficient (AHL*2)
RLA
EXX
DJNZ PF2 ;loop for 24
LD A,C
RET ;exit
FLAG DB 0

1 in the FLAG variable in case of overflow of the result; although very often programs are well thought out and there is no need for it. All possible subsequent operations (addition, subtraction) with the answer are the same as in division.

If you figure it out, we think you will be able to easily modify the procedures for a larger number of bytes to increase the accuracy of calculations. We remind you that the procedures for 3-byte numbers can be used for counting both integers and fractions.

To be continued.

Contents of the publication: ZX Format #07

  • From the Authors
    Update on SMUC, distribution issues, and plans for future ZX Format issues. Authors address outdated SMUC info and distribution problems of ZF-6. Upcoming content includes game descriptions and new projects.
  • Аторы журнала
    Contact information and editorial team details for ZX-Format No.7. Provides mailing and electronic addresses, as well as contact phone numbers. Information on the availability of their website and specific contact instructions.
  • Содержание номера
    The article provides an overview of notable software releases on the St. Petersburg market for autumn. It also includes detailed descriptions of games, programming tips, and hardware projects. Interviews, philosophical tales, and reader letters enrich the issue.
  • Игрушки - Welcome
    An overview of software novelties for ZX Spectrum, including games like 'Los Angeles Drugs Bust' and 'Jungle Warfare'. Each game description provides insights into graphics, gameplay, and features. A variety of genres from action to strategy are covered, showcasing the diversity of software offerings.
  • Игрушки - Алешкин А.В.
    The article describes the game 'TAI-PAN' as an arcade-economic game set in the 19th-century East, focusing on trading and survival amidst pirates and danger. It details the gameplay mechanics, such as trading goods, managing finances, and navigating seas with different ships. Despite its engaging plot and interface, the game didn't achieve much popularity in Russia.
  • Игрушки - Soft
    A whimsical narrative in a fantastical world where colors converse with the Last, a character recounting tales of ancient humans, coders, and a mysterious past. The story explores themes of language, translation, and the creation of 'the Last' amidst fantastical beings like flying hippos and sea giraffes. It serves as a fictional narrative with humorous elements, blending science fiction with satire.
  • Игрушки - Alex ASP
    A parody on Tolkien's 'The Lord of the Rings' named 'Bored of the Rings' by Delta 4 is explored. The text references adaptations, humorous adventures of characters like Fordo and Bimbo, and differing versions from Delta 4 over the years. Anticipated prequels and correspondence excerpts with Delta 4's Fergus McNeill are mentioned.
  • Игрушки - Гил-Гелад
    The article provides a detailed guide on navigating the 3D Construction Kit interface for ZX Spectrum. It explains menu options for file management, game setup, and in-game conditions. Additionally, it covers object creation, editing, and logic implementation within the program.
  • Программистам - Дмитрий Рудовский
    The article concludes the description of BB commands and provides tips on their usage. It details the usage of the CLOCK command for time and alarm management on ZX Spectrum. Additionally, it explains the SORT command for array sorting and introduces new logical and mathematical functions.
  • Программистам - Angel
    Introduction to assembly programming for beginners, covering basic concepts and commands. Detailed explanation of processor registers and flags, with examples. Offers practical advice on transitioning from Basic to assembly language.
  • Программистам - GreenFort
    Discussion on fast calculations in assembler for tasks like vector graphics and astronomy. Describes procedures for binary division and multiplication, with examples for different byte sizes. Highlights the adaptability of these methods for increased precision.
  • Программистам - TP, Stinger
    Detailed technical description of the Mod file format for music composition on ZX Spectrum, focusing on structure and data offsets for title, instruments, and patterns.
  • Программистам - Research
    The article describes the capabilities and limitations of the Convert program, focusing on its use for converting images to the BMC format. It includes technical details about the program's functions, such as dithering methods, sprite and screen format output, and the removal of extraneous dots. Additionally, the article briefly discusses the source code of X-Color and its potential applications.
  • Обзор
    The article discusses the ENLiGHT'97 demo-party held in St. Petersburg on August 24, 1997, featuring platforms like Spectrum, Amiga, and PC. The event attracted around 1100 delegates, leading to overcrowding and technical issues, which caused the cancellation of the second day. Despite these issues, the event was generally enjoyable, and there is hope for another event in 1998.
  • Обзор
    Review of VideoFAIR exhibition in Manezh with highlights on video and audio equipment. Amiga-service and various companies showcased their technological advancements in video editing and broadcast systems. Notable innovations include 3D laser-scanned displays and professional audio solutions.
  • Железо - Nemo
    Discussion of KAY technology export to decentralize Spectrum production. Highlights potential benefits and challenges of local manufacturing. Emphasizes quality assurance and support systems.
  • Железо
    The article describes the development of a new Scorpion motherboard, focusing on enhancing graphics, speed, and compatibility with modern peripherals like IBM keyboards and mice. It introduces the GMX (Graphic Memory Extension) board, designed to upgrade existing Scorpion models to match the capabilities of the new motherboard. The GMX board offers significant improvements in memory, graphics, and processing speed, while maintaining compatibility with ZX Spectrum and Pentagon standards.
  • Железо
    The article provides a detailed overview of two popular audio amplifiers for ZX Spectrum users in St. Petersburg. It highlights the advantages and specifications of the 2 X 2W low-voltage amplifier and the 2 X 22W car amplifier. The article also includes a price list and ordering instructions through the 'Nemo' company.
  • Примьера
    The article describes the improvements and features of the Turbo Assembler version 1.1 for ZX Spectrum. It highlights the differences from version 1.0, such as bug fixes, screen size changes, and added features like line editor and syntax checking. It also details the memory allocation and provides a guide on using the editor and compiler functions.
  • Примьера - STS
    Description of the Riff Tracker MOD-editor for General Sound, its features, and functionalities. Provides detailed instructions on using editing and sample management. Notes on the current version limitations and expected improvements.
  • Примьера - Paul Atrides, Alex Noman
    Presentation of Oberon Creative Pack, consisting of ZX-WinWord and Sprite Cutter. ZX-WinWord is a text editor combining text and graphics with advanced features. Sprite Cutter allows sprite creation and manipulation in various formats.
  • Примьера
    Presentation of the second demo version of the game Headball by ZX-Masters, discussing its features and improvements since the first demo. The game offers two-player mode, four levels, three types of projectiles, various options, and computer difficulty settings. Availability of Turbo mode and enhanced synchronization and animation make it unique among other Spectrum games.
  • Интервью - Ruster
    Interview with Digital Reality about ongoing projects like DOOM and Paradise Lost. Discussion of challenges and progress in game development. Preview of their submissions for the ENLiGHT event.
  • Интервью - Ruster
    Interview with members of the newly formed group EXTREME. They work on demos for Spectrum and Amiga platforms and discuss their team members and activities. The interview also touches upon the state of the Amiga scene in Moscow.
  • Интервью - Борис Прытков
    Interview with Samara-based Spectrum enthusiasts discussing their achievements and challenges. Emphasis on community building and publication of Oberon magazine. Efforts to establish a Spectrum network and convert the game WALKER.
  • Интервью - Борис Прытков
    The article is an interview with members of the group Flash inc. discussing their projects for ZX Spectrum and PC, including a music editor with an innovative interface and a new multicolor graphic editor.
  • Интервью - Михаил Акимов
    Interview with Moscow-based group Progress discussing their current work on Spectrum demos, plans for future projects on Amiga, and opinions on the Russian demoscene.
  • Интервью - Михаил Акимов
    Interview with Felix about changes in the tech landscape, the enduring appeal of Amiga despite PC dominance, and his work on 'Winnie the Pooh - 2' for Spectrum.
  • Интервью - Ruster
    Interview with Slash about the ENLiGHT event, including sponsorship issues, attendee behavior, and the quality of music and demos. Discussion of the current state of the Spectrum and Amiga markets. Commentary on music trackers and the future of hardware development.
  • Интервью - Ruster
    Interview with V. Mednonogov after ENLiGHT'97 discussing impressions of the event, future of Spectrum, and his current project 'Black Raven'. Mednonogov shares his views on new hardware and software development and the importance of copyright. He also discusses his plans for upcoming projects and the challenges faced in game development.
  • Здесь был ты
    A satirical guide to gaining power and invisibility using magical rituals and Orbit gum.
  • Здесь был ты - Saggitarius
    A contemplative novella about a man's existential journey after encountering a mysterious individual offering a device called the Stop Crane. Through flashbacks, the protagonist reflects on his life, uniqueness, and his desire to break free from societal constraints. Ultimately, he faces the moral dilemma of using the Stop Crane to transcend time and existence.
  • Почта - Eagle Soft
    Critique of ZX-Spectrum software, highlighting the limitations of current programs and recommending the removal of outdated tools. Discussion on the limitations of assembly programs and the need for more efficient assemblers like M80. Evaluation of current music and graphic editors, with a focus on the redundancy of certain applications.
  • Почта
    Discussion of reader inquiries on ZX Format distribution and content. Responses include details on acquiring issues and technical insights on the KAY-256 computer. The magazine also addresses criticism of its market outlook article.
  • Почта
    This advertisement highlights XL Design Inc.'s software distribution campaign, offering games like 'Plutonia' and upcoming releases such as 'Mortal Kombat'. Mouse controllers are promoted with humorous selling points and pricing details. Studio LOGROS provides a wide range of software and peripherals, with options for local and remote purchases.
  • Разное - Александр Сысоев
    The article discusses the creation of an RPG game by the OBERON GROUP, inspired by 'Eye of Beholder'. It describes the game's humorous plot set in a distant galaxy and the battle against invaders on a planet named Agima. The team invites musicians, artists, coders, and scriptwriters for collaboration.
  • Разное - Viator
    The article describes the development of a new graphics editor called STATE OF THE ART for ZX Spectrum, aiming to improve upon existing editors like ART-STUDIO and ARTIST-2. The team AVALON, inspired by feedback from the SPECCY artist community, incorporates features from editors on Amiga and PC, while also addressing specific user requests. Key features include a user-friendly interface, enhanced magnify mode, advanced shape and window manipulation, and optimized performance.
  • Разное
    Discussion on enhancing consumer quality of Spectrum computers without altering their technical specifications. Suggestions include improving existing support, developing platform ideology, and structural changes. The article also touches on the potential of electronic books and their commercial viability.
  • Amiga Club - Максим Петров
    The article describes the author's admiration for the Amiga computer, emphasizing its aesthetic and technical merits compared to other platforms. It explores the author's programming experiences on Amiga, highlighting its efficiency and the impressive capabilities of its new hardware upgrades. The article concludes by reflecting on the unique community and passion of Amiga enthusiasts.