Question :1 Design and implement an 8086 Assembly PROCEDURE that analyzes a
predefined array of 12 signed integers stored in memory and performs the following:
Solution
Algorithm
1. System Initialization: Initialize the system environment. Set up the DATA SEGMENT
base address configuration and map it into the DS (Data Segment) register to enable
universal memory addressing.
2. Pointer and Index Initialization: Load the memory offset address of the predefined
integer array (ARR) into the source index register SI.
3. Loop Counter Configuration: Set the deterministic loop counter register CX to 12,
representing the total cardinality of the target array elements.
4. Variable Reset Sequence: Programmatically purge and reset the memory state
variables ODD and NEG_ODD to 0000H via the primary execution block.
5. Procedure Interruption: Execute a explicit near call instruction (CALL
CHECK_ARRAY) to pass machine state control to the dedicated processing
sub-routine.
6. Register Preservation Stack Sequence (Inside Sub-routine):
○ Push SI onto the stack architecture to preserve the external array traversal
state.
○ Push CX onto the stack to lock the master tracking loop index.
○ Push DX and BX onto the stack layers to isolate localized operations from
corrupting main thread calculations.
7. Iterative Core Loop Block (L1):
○ Fetch the current 16-bit word-sized integer element from the memory location
pointed by SI into register AX.
○ Duplicate the fetched bit pattern from AX into the backup register DX for
context-restoration.
○ Perform a logical bitwise right shift (SHR AX, 1) by one position. This shifts
the Least Significant Bit (LSB) into the CPU's internal Carry Flag (CF).
○ Evaluate the state of CF. If CF == 0, execute a conditional branch (JNC SKIP)
to bypass odd number tracking.
○ If CF == 1, increment the memory variable ODD by 1.
○ Restore the original 16-bit word context into AX from the backup register DX.
○ Perform a mathematical comparison (CMP AX, 0) to ascertain the algebraic
sign polarity.
○ If AX >= 0, trigger a conditional branch (JGE SKIP) to bypass negative
tracking.
○ If AX < 0, programmatically increment the targeted memory variable
NEG_ODD.
8. Memory Traversal Control: Increment the source index register SI by 2 bytes (ADD
SI, 2) to position the pointer onto the next 16-bit boundary. Decrement CX and repeat
the loop structure (LOOP L1) until CX reaches zero.
9. State Restoration Block: Pop the stored registers (BX, DX, CX, SI) in reverse order to
ensure precise state alignment. Return control to the main system thread via RET.
10.System Termination: Move output values from variables to primary execution
registers for debug visibility and issue the hardware halt instruction (HLT).
Code
ORG 100H ; Directive to specify code starting address in memory
.DATA ; Declaration segment for system state variables
ARR DW 3, 5, 8, -12, 11, -7, 0, 15, -9, 4, 14, -3 ; Array containing 12 signed word
integers
ODD DW 0000H ; Memory location to aggregate total count of odd integers
NEG_ODD DW 0000H ; Memory location to aggregate total count of negative odd
integers
.CODE ; Code compilation and execution segment
MAIN PROC
MOV AX, @DATA ; Load the absolute base memory address of the data segment
MOV DS, AX ; Synchronize the Data Segment register with the base address
XOR AX, AX ; Programmatically clear AX to eliminate garbage values
MOV AX, 0000H ; Double verification clear sequence for data alignment
MOV SI, OFFSET ARR ; Initialize base pointer; load starting address of ARR into
SI
MOV CX, 000Ch ; Configure loop execution counter with exactly 12 loops (12
decimal)
CALL CHECK_ARRAY ; Transfer CPU execution context to the array processing
sub-routine
MOV AX, [ODD] ; Move accumulated odd integers count into AX for evaluation
MOV BX, [NEG_ODD] ; Move accumulated negative-odd count into BX for
verification
NOP ; No-Operation instruction inserted for pipeline alignment
HLT ; Trigger hardware level halt to terminate processing execution
MAIN ENDP
CHECK_ARRAY PROC ; Sub-routine block optimized for array classification
PUSH SI ; Protect main thread source index pointer by pushing to Stack
PUSH CX ; Save main loop count context to prevent execution corruption
PUSH DX ; Preserve DX data register configuration state on Stack
PUSH BX ; Secure BX register structure prior to localized calculations
L1:
MOV AX, [SI] ; De-reference memory pointer SI and extract current 16-bit
integer
MOV DX, AX ; Establish a full data backup of the current element inside DX
XOR BX, BX ; Clear local workspace register BX
MOV BX, AX ; Mirror AX to BX for localized architectural manipulation
SHR AX, 1 ; Execute logical shift right; pushes structural LSB into Carry Flag
JNC SKIP ; Evaluates Carry Flag; if CF=0 (Even), execute branch to SKIP
label
INC [ODD] ; Mathematical condition met (CF=1); increment total odd counter
MOV AX, DX ; Restore original unshifted integer bit profile back into AX
CMP AX, 0000H ; Mathematically evaluate integer against zero threshold
JGE SKIP ; If integer is positive or zero, bypass negative tracking module
INC [NEG_ODD] ; Condition met (Negative & Odd); increment specific memory
variable
SKIP:
ADD SI, 0002H ; Move index register by two bytes to access next 16-bit word
element
LOOP L1 ; Decrement CX; if CX != 0, execute conditional jump back to L1
POP BX ; Restore original BX state from stack architecture
POP DX ; Retrieve preserved DX register content from Stack
POP CX ; Re-establish main thread loop execution count
POP SI ; Re-align original array memory pointer for main thread
RET ; Execute near return to transfer control back to call site
CHECK_ARRAY ENDP
END MAIN
Code Output
Theoretical Explanations
Procedural Modularization vs. Inline Code Expansion: The architectural optimization strategy
mandates modular procedures (PROC) instead of linear inline microcode deployment. This
programmatic isolation enforces the separation of concerns paradigm. Inline replication scales linearly
in code segment memory allocation (O(N . M) instructions), inflating the executable footprint.
Conversely, procedural abstraction encapsulates the algorithm in a single memory region, resulting in
a static O(1) memory footprint overhead, dramatically improving system L1 cache hit metrics and
compiler optimization opportunities.
Register Preservation Stack Topology: To maintain system state integrity and avoid context register
collision across asynchronous execution scopes, a strict LIFO (Last-In-First-Out) hardware stack
topology is deployed. The sub-routine alters critical structural indexing registers (SI, CX, DX, BX).
Un-isolated state modification introduces undefined programmatic behavior in the parent routine.
PUSH operations store these 16-bit states onto the stack segment before execution, and POP
operations restore them in precise inverse sequence, ensuring zero state distortion upon procedural
termination.
Question 2 : Write an 8086 Assembly program that divides an 8-bit signed dividend by
an 8-bit signed divisor using only logical, shift, and add/subtract operations.
Solution
Algorithm
1. System Ingress: Initialize system parameters and assign data segment pointers to
establish access to operands.
2. Operand Ingress Parsing: Extract the 8-bit signed DIVIDEND and DIVISOR from
memory locations, mapping them respectively into the 8-bit registers AL and BL.
3. Divide-by-Zero Exception Routine: Evaluate the divisor bit state (CMP BL, 0). If a
null divisor state is encountered, immediately execute a branch to
ZERO_ERR_LABEL to toggle error flags and bypass hardware faults.
4. Sign Bit Tracking Integration: Clear register CH to act as an absolute algebraic
inversion tracker.
5. Dividend Polarity Assessment: Check if AL < 0. If negative, invoke the two's
complement arithmetic inversion instruction (NEG AL) and toggle the inversion
tracker bit using XOR CH, 1.
6. Divisor Polarity Assessment: Check if BL < 0. If negative, invoke NEG BL to
generate the absolute scalar magnitude and toggle the inversion tracker via XOR CH,
1.
7. Execution Loop Concurrency (MY_SUB_LOOP):
○ Compare current scalar dividend AL against scalar divisor BL.
○ If AL < BL, the mathematical subtraction loop terminates; branch to
MY_SUB_DONE.
○ Otherwise, execute structural subtraction: SUB AL, BL.
○ Increment the 8-bit counting register (INC CL) to track the integrated quotient
count.
○ Force an unconditional loop recycle back to MY_SUB_LOOP.
8. Output Structuring Sequence: Store the remaining scalar value left in AL directly into
the REMAINDER variable.
9. Algebraic Complement Restoration: Assess the sign inversion register tracker (CMP
CH, 1). If valid, execute NEG CL to restore the correct two's complement sign to the
quotient.
10.State Egress Saving: Write the output register CL to QUOTIENT, configure
verification diagnostic registers AX and BX, and exit the program safely.
Code
ORG 100H ; Define standard base offset for COM executable structure
.DATA ; Data allocation segment for processing variables
DIVIDEND DB -25 ; 8-bit signed integer dividend variable assignment
DIVISOR DB 4 ; 8-bit signed integer divisor variable assignment
QUOTIENT DB 00H ; Memory space allocated for final quotient output storage
REMAINDER DB 00H ; Memory space allocated for final remainder output
storage
ERR_FLAG DB 00H ; System exception flag register for divide-by-zero
occurrences
.CODE ; Microcode binary instructions execution block
MAIN PROC
MOV AX, @DATA ; Load target data segment location address structure
MOV DS, AX ; Align the system segment pointer with data space base
MOV AL, DIVIDEND ; Load primary 8-bit operand (dividend) directly into AL
MOV BL, DIVISOR ; Load secondary 8-bit operand (divisor) directly into BL
MOV ERR_FLAG, 00H ; Explicit initialization reset of the exception register
CMP BL, 00H ; Perform arithmetic check to protect against zero division
JE ZERO_ERR_LABEL ; Hardware check failure: branch to exception routine if
BL=0
XOR CH, CH ; Reset sign tracking register; CH=00H initially
MOV CL, 00H ; Set local workspace quotient accumulator to zero
CMP AL, 00H ; Evaluate numerical algebraic state of dividend register AL
JGE CHK_DIVISOR ; If AL is greater than or equal to zero, skip inversion phase
NEG AL ; Apply two's complement inversion to yield absolute magnitude
XOR CH, 01H ; Bitwise complement tracker flag to denote one negative input
CHK_DIVISOR:
CMP BL, 00H ; Evaluate numerical algebraic state of divisor register BL
JGE MY_START ; If BL is greater than or equal to zero, skip inversion phase
NEG BL ; Apply two's complement inversion to establish absolute value
XOR CH, 01H ; Toggle sign inversion tracking flag via XOR manipulation
MY_START:
XOR CL, CL ; Clear quotient counter register completely to prepare for loop
MOV CL, 00H ; Enforce explicit literal initialization value allocation
MY_SUB_LOOP:
CMP AL, BL ; Compare current structural state of dividend against divisor
scalar
JB MY_SUB_DONE ; Conditional branch: if AL < BL, subtraction loop is
finished
SUB AL, BL ; Implement subtraction sequence; decrement dividend by divisor
scalar
INC CL ; Increment computational loop accumulator tracker variable by 1
JMP MY_SUB_LOOP ; Unconditional cycle command to execute subsequent loop
verification
MY_SUB_DONE:
MOV REMAINDER, AL ; Transfer final remaining dividend scalar into target
memory location
CMP CH, 01H ; Evaluate algebraic inversion tracker register state
JNE SAVE_RES ; If CH != 1, polarity configuration is correct; skip negation
NEG CL ; Invert quotient to re-establish proper negative representation
SAVE_RES:
MOV QUOTIENT, CL ; Commit calculated quotient state to standard memory
variable
MOV AL, QUOTIENT ; Route quotient into AL for unified external register
display
MOV AH, REMAINDER ; Route remainder into AH for cohesive multi-register
access
MOV BX, 0001H ; Inject validation confirmation identifier code into register BX
JMP MY_EXIT ; Direct unconditional branch to close current execution context
ZERO_ERR_LABEL:
MOV ERR_FLAG, 01H ; System failure state triggered; raise division by zero error
flag
MY_EXIT:
HLT ; Put processor into low-power halting status state
MAIN ENDP
END MA
Code Output
Theory
Algorithmic Abstraction of Repeated Subtraction Processing: The implementation replicates
integer division through a progressive additive-inverse loop, bypassing the native CPU
hardware pipeline execution units for DIV/IDIV. The operational theorem dictates that for
any integers A and B, A = (B .Q) + R, where R < B. By continuously looping the arithmetic
primitive SUB A, B, the processor monitors compliance with this inequality. The iteration
count explicitly correlates to the mathematical quotient Q, while the remaining
un-subtractable operand profile represents the structural remainder R.
Sign Restoration Integration and Division Zero Exception Containment: Signed execution
structures cannot directly process pure magnitudes without algorithmic distortion. The system
normalizes incoming vectors to a first-quadrant positive spatial domain via a conditional NEG
operation, utilizing an internal state register bit tracker (CH) to capture inputs mapping to
different mathematical quadrants. If Sign(A) \neq Sign(B), an XOR check mandates a final
mathematical negation step. To prevent an infinite loop scenario resulting from a zero divisor
(A - 0 = A), a priority hardware check (CMP BL, 0) screens the input stream, isolating null
inputs to ensure system uptime.
Question 3 : Code Optimization and Functional Expansion
Solution
Algorithm
1. Data Grid Allocation: Allocate a contiguous 5-byte block in memory using array
structural primitives (DUP(0)) to construct an analytical data sink (FACT_ARRAY).
2. Context Setup: Map the absolute data segment properties into register DS to establish
correct memory segmentation addressing.
3. Loop Condition Vectoring: Configure register CL as a static benchmark reference
holding the value 5. Initialize register AL to 1 as the factorial multiplicative identity
element.
4. Multiplier Pointer Instantiation: Load the relative structural tracking address of
FACT_ARRAY into register SI and set multiplier scalar tracker BL to 1.
5. Highly-Optimized Mathematical Loop (CALC_LOOP):
○ Execute an explicit byte-purging command (XOR AH, AH) to prevent legacy
higher-order bit data pollution during multiplication operations.
○ Execute the word-scaling assembly primitive MUL BL. This instruction scales
the accumulator content (AL) by the current factor scalar (BL), writing the
results to the unified AX register.
○ Commit the calculated value from AL directly to the de-referenced pointer
memory address [SI].
○ Increment the tracking memory location index (INC SI) by 1 byte to step to
the next array element.
○ Increment the current calculation factor scalar value (INC BL).
○ Perform an evaluation step (CMP BL, 6) against the processing limit
boundary.
○ If BL != 6, trigger a short conditional jump (JNE CALC_LOOP) to process
the next factorial calculation.
6. Program Termination Sequence: Inject validation diagnostic signature hex arrays into
AX and invoke the machine halt sequence (HLT).
Code
ORG 100H ; Base system memory positioning definition directive
.DATA ; Allocate system storage space for persistent variables
FACT_ARRAY DB 5 DUP(00H) ; Allocate 5 consecutive bytes of zero-initialized
memory space
.CODE ; Segment container for logic processing directives
MAIN PROC
MOV AX, @DATA ; Retrieve absolute programmatic segment address of
variables
MOV DS, AX ; Bind segment register DS to enable reliable memory access
XOR AX, AX ; Enforce localized general register diagnostic clear
MOV CL, 05H ; Set target iteration tracking length explicitly to 5
MOV AL, 01H ; Initialize factor accumulator tracking state to mathematical 1
MOV BL, 01H ; Set structural starting multiplier value to base 1
MOV SI, OFFSET FACT_ARRAY ; Point index register SI directly to the array's first
memory byte
CALC_LOOP:
XOR AH, AH ; Purge AH register; prevents high-byte pollution prior to MUL
MOV AH, 00H ; Reinforce execution space clearing for arithmetic alignment
MUL BL ; Multiply AL by BL; result is stored across the entire AX register
MOV [SI], AL ; De-reference SI and commit the low-byte product directly to
memory
INC SI ; Advance memory tracking pointer to the adjacent array index byte
INC BL ; Advance scalar loop integer multiplier to the next sequential digit
CMP BL, 06H ; Perform boundary limit check against terminal criteria (6
decimal)
JNE CALC_LOOP ; Conditional branch: if limit not reached, cycle back to
CALC_LOOP
MOV AX, 00FAH ; Load target success verification status flag into AX register
MOV BX, OFFSET FACT_ARRAY ; Load final base array location index to verify
storage via memory dump
HLT ; Execute hardware core halt to pause processing execution
MAIN ENDP
END MAIN
Code Output
Theory
● Mitigation of Destructive Input and Execution Inefficiencies: Legacy algorithms often
degrade structural execution loops through destructive operations on control registers
(such as directly calling DEC CL), which completely erases the historical execution
trace. The modernized architecture preserves structural variables intact by utilizing
decoupled tracking nodes (BL). This decoupling facilitates persistent diagnostic
inspection and expands functionality from a single computational point to a
contiguous multi-byte memory array (1! 5!), transforming isolated data points into a
sequential operational matrix.
● Instruction Pointer (IP) Vectoring Mechanics and Clock-Cycle Optimization: The
Instruction Pointer (IP) functions as a dedicated 16-bit tracking register that
continuously holds the offset memory address of the next machine instruction
scheduled for execution. When a conditional branch (JNE) evaluates to true, the CPU
updates the IP register with the target label's relative offset address, altering the
instruction pre-fetch queue. By replacing multiple inline code segments with a loop
macro, instruction density drops significantly, optimizing cache localization, reducing
pipeline stalls, and minimizing the overall structural memory footprint.
Question 4 : Design an 8086 Assembly program that operates on a 16-bit hexadecimal
number stored in memory and performs the following:
Solution
Algorithm
1. Input State Data Aggregation: Define the target 16-bit hexadecimal string parameter
(2AF4H) inside memory variable HEX_NUM. Allocating tracking variables
EVEN_SUM and GT_9_COUNT within the data structure.
2. System Memory Frame Stabilization: Bind data segment indicators to DS to handle
data reference operations cleanly.
3. Register Resource Allocation: Load the target 16-bit hex data from memory into
tracking workspace register BX. Setup loop tracker CX with a literal value of 4,
processing all four distinct 4-bit hexadecimal nibbles.
4. Nibble Isolation Core Architecture (EXTRACT_LOOP):
○ Mirror the operational state of workspace register BX into AX.
○ Apply an explicit bitwise mask (AND AX, 000FH) to isolate the lowest 4 bits
and purge the higher-order bits.
○ Evaluate numerical boundary thresholds (CMP AX, 9).
○ If the value is le 9, execute a conditional branch (JBE CHECK_EVEN) to skip
alphabetic symbol processing.
○ If the value is > 9 (A through F), increment the global tracker memory variable
GT_9_COUNT.
5. Parity Classification Segment (CHECK_EVEN):
○ Execute an atomic bitwise test check instruction (TEST AL, 1) against the
Least Significant Bit (LSB) of the isolated nibble.
○ If the LSB is 1 (indicating an odd number), branch to NEXT_NIBBLE.
○ If the LSB is 0 (indicating an even number), add the numeric nibble value
directly to the tracking variable EVEN_SUM.
6. Data Shift Synchronization Block (NEXT_NIBBLE):
○ Execute a logical right shift (SHR BX, 4) on the workspace register to discard
the processed 4-bit nibble and position the next hex digit into the lowest
parsing slot.
○ Loop back (LOOP EXTRACT_LOOP) until CX decrements to 0.
7. Egress Data Loading: Write processing values back into visible working registers and
invoke HLT.
Code
ORG 100H ; Allocate standard operating system memory position framework
.DATA ; Establish memory declaration parameters for evaluation elements
HEX_NUM DW 2AF4H ; Define 16-bit hexadecimal source variable for deep
analysis
EVEN_SUM DB 00H ; Allocate memory counter to sum values of even hex digits
GT_9_COUNT DB 00H ; Allocate memory counter to track frequency of letters
(A-F)
.CODE ; Code block for structural compilation execution
MAIN PROC
MOV AX, @DATA ; Retrieve absolute memory segment layout address locations
MOV DS, AX ; Align Data Segment tracking pointer with targeted variables
MOV BX, [HEX_NUM] ; Load the complete 16-bit hex array vector into register
BX
MOV CX, 0004H ; Set loop processing limits to 4; each loop processes a 4-bit
nibble
EXTRACT_LOOP:
MOV AX, BX ; Mirror current structural state of BX into working register AX
AND AX, 000FH ; Apply bitwise mask; isolates lowest 4 bits and clears the
upper 12 bits
CMP AX, 0009H ; Algebraically evaluate the numeric state against value 9
JBE CHECK_EVEN ; If value is within 0-9 boundary range, skip letter counter
update
INC [GT_9_COUNT] ; Hex digit is alphabetic (A-F); increment greater-than-9
counter
CHECK_EVEN:
TEST AL, 01H ; Perform bitwise test on LSB to determine digit's odd/even
status
JNZ NEXT_NIBBLE ; Zero flag not set (LSB=1); digit is odd, bypass summation
engine
ADD [EVEN_SUM], AL ; Parity verification successful (Even); accumulate value
into EVEN_SUM
NEXT_NIBBLE:
SHR BX, 4 ; Shift register right by 4 bits; brings next high nibble into parsing
slot
LOOP EXTRACT_LOOP ; Decrement CX; if CX > 0, branch back to process next
nibble
MOV AL, [EVEN_SUM] ; Load final accumulated even digit sum into AL for
inspection
MOV BL, [GT_9_COUNT] ; Load total alphanumeric character count into BL for
inspection
HLT ; Halt execution processor pipeline cleanly
MAIN ENDP
END MAIN
Code Output
Theory
Granular Extraction via Bitwise Masking and Logical Shifting: A 16-bit hexadecimal data
word comprises four independent 4-bit architectural fields termed nibbles. Isolating these
configurations sequentially requires coordinated bit-masking and logical shifting operations.
The AND AX, 000FH bit-mask zero-initializes the upper twelve bits of the register while
leaving the lower 4 bits completely untouched, isolating the target digit. Once processed, a
logical right shift (SHR BX, 4) discards the current nibble and shifts the adjacent high-order
bit field into the parsing window, maintaining a clean data pipeline throughout execution.
Hexadecimal Alphanumeric Thresholding and Hardware Parity Evaluation: Alphanumeric
parsing relies on comparing structural values against the numerical baseline (9). If a digit
exceeds this value (10 X 15), it maps to the hexadecimal character space A-F. Parity
detection is optimized by analyzing the LSB via the TEST AL, 01H instruction. Since all odd
numbers require the 2^0 bit to be enabled, checking the LSB allows the CPU to immediately
determine parity and branch conditionally without executing heavy division sub-routines.
Question 5 : Design an 8086 Assembly decision-making system that classifies an 8-bit
signed input number into one of the following categories:
Solution
Algorithm
1. System Variables Structuring: Declare target storage elements INPUT_NUM and
tracking register CATEGORY within the data block.
2. Data Pointer Setup: Link the structural storage area properties to the DS register for
data segment management.
3. Zero Bound Isolation: Load INPUT_NUM into register AL. Execute an explicit
condition check (CMP AL, 0). If equal, branch to IS_ZERO to classify it under
category value 3.
4. Polarity Routing Sequence: Execute a signed conditional jump check (JL
IS_NEGATIVE). If the value evaluates to true, redirect the execution flow to the
negative analysis module. Otherwise, proceed linearly to IS_POSITIVE.
5. Positive/Prime Evaluation Module (IS_POSITIVE):
○ If AL <= 1, it cannot be prime; branch immediately to NOT_PRIME.
○ If AL == 2 or AL == 3, it is definitively prime; branch to IS_PRIME.
○ For values >3, clear AH and execute experimental division by 2 (DIV BL).
Check remainder AH. If AH == 0, it is a non-prime multiple; branch to
NOT_PRIME.
○ Reload the original variable data into AL, clear AH, and divide by 3. Check
remainder AH. If AH == 0, branch to NOT_PRIME.
○ If it passes both tests, route the logic flow to IS_PRIME to apply category
value 4.
6. Negative Multiplicity Evaluation Module (IS_NEGATIVE):
○ Transform the signed data stream to an absolute positive scalar value using the
two's complement arithmetic operator NEG AL.
○ Load divisor value 4 into BL, clear AH, and execute division (DIV BL).
○ Evaluate remainder AH. If AH == 0 (meaning a perfect multiple of 4), assign
category value 1 (NEG_MULT_4).
○ If a remainder exists, assign category value 2.
7. System Outcome Synchronization: Consolidate execution blocks into a unified output
hub (EXIT), loading the final category value into DL before executing HLT.
Code
ORG 100H ; Initialize code generation matching standard system architecture
offsets
.DATA ; Allocation segment for input testing arrays
INPUT_NUM DB -12 ; 8-bit signed integer input operand intended for parsing
CATEGORY DB 00H ; Storage container for the assigned classification category
index
.CODE ; Primary execution segment containing decision architecture
MAIN PROC
MOV AX, @DATA ; Retrieve absolute base memory location tracking addresses
MOV DS, AX ; Align segment tracker register DS with variable space
MOV AL, INPUT_NUM ; Load target 8-bit signed input variable into register AL
CMP AL, 00H ; Perform conditional comparison against neutral element zero
JE IS_ZERO ; Conditional branch: if input value matches zero, jump to
IS_ZERO
JL IS_NEGATIVE ; Conditional branch: if input value is less than zero, jump to
negative module
IS_POSITIVE: ; Execution branch optimized for positive value sorting
CMP AL, 01H ; Compare input value against the upper limit of non-prime
values (1)
JLE NOT_PRIME ; If value is less than or equal to 1, classify as non-prime
CMP AL, 02H ; Evaluate number against the lowest prime integer boundary (2)
JE IS_PRIME ; Exact match confirmed: route flow directly to prime handler
CMP AL, 03H ; Evaluate number against the next sequential prime baseline (3)
JE IS_PRIME ; Exact match confirmed: route flow directly to prime handler
MOV BL, 02H ; Configure trial division testing scalar to factor of 2
XOR AH, AH ; Completely clear high-byte AH to prevent remainder
corruption
DIV BL ; Perform division; AL / 2, remainder maps directly into register AH
CMP AH, 00H ; Evaluate remainder; check if number is an even multiple of 2
JE NOT_PRIME ; Perfect divisibility confirmed (Even compound number);
branch to NOT_PRIME
MOV AL, INPUT_NUM ; Re-extract original baseline integer value from memory
into AL
MOV BL, 03H ; Configure next trial division testing scalar to factor of 3
XOR AH, AH ; Clear high-byte register AH to prevent remainder data pollution
DIV BL ; Execute division operation; AL / 3, remainder updates inside AH
CMP AH, 00H ; Evaluate remainder; check if number is a multiple of 3
JE NOT_PRIME ; Perfect divisibility confirmed; branch to non-prime
classification
IS_PRIME:
MOV CATEGORY, 04H ; Evaluation passed: assign Category 4 status to variable
JMP EXIT ; Unconditional branch to unified program termination sequence
NOT_PRIME:
MOV CATEGORY, 05H ; Validation failed: assign Category 5 status to variable
JMP EXIT ; Unconditional branch to unified program termination sequence
IS_NEGATIVE: ; Processing module optimized for negative integers
NEG AL ; Convert negative signed value into absolute positive scalar
magnitude
MOV BL, 04H ; Establish divisional validation metric factor to 4
XOR AH, AH ; Ensure high-order byte register AH is cleared of garbage values
DIV BL ; Execute division process; absolute AL scalar value divided by 4
CMP AH, 00H ; Evaluate remainder register to check for perfect divisibility
JE NEG_MULT_4 ; Remainder is zero: branch to dedicated Category 1 handler
MOV CATEGORY, 02H ; Remainder is non-zero: assign Category 2 status to
variable
JMP EXIT ; Terminate conditional check sequence; branch to EXIT label
NEG_MULT_4:
MOV CATEGORY, 01H ; Assign Category 1 status (Negative multiple of 4) to
variable
JMP EXIT ; Terminate conditional check sequence; branch to EXIT label
IS_ZERO:
MOV CATEGORY, 03H ; Neutral condition met: assign Category 3 status to
variable
EXIT:
MOV DL, CATEGORY ; Route final classification index value to register DL for
output inspection
HLT ; Halt execution pipeline smoothly
MAIN ENDP
END MAIN
Code Output
Theory Explanation
Hierarchical State Segmentation and Optimization of Conditional Branching: The
classification algorithm minimizes execution latency by prioritizing boundary checks in a
strict top-down hierarchy. Checking for zero first using a single conditional branch (JE)
removes the neutral origin point from the processing stream immediately. This early isolation
prevents downstream processing paths from running redundant sign or mathematical sorting
operations, reducing unnecessary comparison cycles and optimizing the processor's branch
prediction efficiency.
Deterministic Modular Verification of Small Integer Primes: For 8-bit inputs within typical
lab testing scopes, deploying a complex prime checking algorithm adds unnecessary
complexity and computational overhead. The microcode optimizes this by utilizing a targeted
multi-stage trial division structure. Numbers 1 are immediately filtered out as non-prime,
while base prime values (2 and 3) are handled through direct conditional matches. Larger
values are verified via localized trial divisions using prime factors 2 and 3, creating a highly
optimized, deterministic classification matrix that minimizes memory footprint while
maintaining perfect execution accuracy.