Printing a number in binary
A program that prints a number in binary representation.
Program source code
title .model small .stack 100h code segment public assume cs:code main proc mov al, 142 ; Copy the number 142 into the al register call PrintBinary ; Call the PrintBinary procedure mov ax, 4C00h ; Copy the termination function number into ah and the value into al int 21h ; Call the interrupt main endp PrintBinary proc push ax ; Save the value of the ax register on the stack push si ; Save the value of the si register on the stack cmp al, 0Fh ; Compare the value in the al register with the number 15 ja Print8Bits ; If the value in the al register is greater than 15, jump to Print8Bits Print4Bits: mov cx, 4 ; Copy the number 4 into the cx register shl al, cl ; Perform a logical shift of the value in the al register 4 bits to the left jmp MainLoop ; Perform an unconditional jump to the MainLoop label Print8Bits: mov cx, 9 ; Copy the number 9 into the cx register MainLoop: cmp cx, 5 ; Compare the counter value with the number 5 jz AddSpace ; If ZF=1, jump to the AddSpace label rol al, 1 ; Rotate the bits in the al register 1 position to the left jc PutOne ; If CF=1, jump to the PutOne label PutZero: mov byte ptr[si], '0' ; Copy the ASCII-0 value into the si register jmp Continue ; Perform an unconditional jump to the Continue label PutOne: mov byte ptr[si], '1' ; Copy the ASCII-1 value into the si register jmp Continue ; Perform an unconditional jump to the Continue label AddSpace: mov byte ptr[si], 20h ; Copy the space value into the si register Continue: inc si ; Increment the si index value by 1 loop MainLoop ; Loop while CX≠0 mov byte ptr[si], 24h ; Copy the string terminator character ($) into the si register mov ah, 09h ; Copy the string output function number into ah pop dx ; Pop the value from the stack into dx. dx = the initial address of si int 21h ; Call the interrupt xor si, si ; Clear the si register pop ax ; Pop the value from the stack into the ax register ret ; Return from the procedure PrintBinary endp code ends end main
1000 1110
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".