Saraharas 0 / 0 / 0 Регистрация: 14.10.2014 Сообщений: 53 |
||||
1 |
||||
13.08.2015, 14:30. Показов 12669. Ответов 2 Метки нет (Все метки)
Здравствуйте! Пишу программу, сортирующую массив. На вход подается число элементов (0<N<10000), затем N чисел через пробел — элементы массива. Вывести нужно сортированный массив.
__________________
0 |
Клюг 7673 / 3188 / 382 Регистрация: 03.05.2011 Сообщений: 8,380 |
|
13.08.2015, 16:22 |
2 |
Подскажите, пожалуйста, в чем ошибка. В слове seсtion буква ‘c’ — русская.
1 |
Saraharas 0 / 0 / 0 Регистрация: 14.10.2014 Сообщений: 53 |
||||
17.08.2015, 13:28 [ТС] |
3 |
|||
Появился еще один вопрос по этой задаче. По условию количество элементов массива заранее неизвестно (но известно, что элементов <10000). Malloc не хотела использовать, поэтому создала массив максимального размера и использую только его часть. Подскажите, пожалуйста, как правильно записать условие выхода из цикла. (на строчках 27 и 58 выдает ошибку: error: expression syntax error).
0 |
Я задал похожий вопрос здесь но я сменил ассемблеры, и вопрос почти полностью изменился, поэтому, чтобы избежать беспорядка, я публикую совершенно новый вопрос. Короче говоря, у меня Windows 7, я только что установил NASM и пытаюсь собрать листинг кода из книги Майкла Абраша под названием Zen of Assembly. Вот код листинга:
;
; *** Listing 2-1 ***
;
; The precision Zen timer (PZTIMER.ASM)
;
; Uses the 8253 timer to time the performance of code that takes
; less than about 54 milliseconds to execute, with a resolution
; of better than 10 microseconds.
;
; By Michael Abrash 4/26/89
;
; Externally callable routines:
;
; ZTimerOn: Starts the Zen timer, with interrupts disabled.
;
; ZTimerOff: Stops the Zen timer, saves the timer count,
; times the overhead code, and restores interrupts to the
; state they were in when ZTimerOn was called.
;
; ZTimerReport: Prints the net time that passed between starting
; and stopping the timer.
;
; Note: If longer than about 54 ms passes between ZTimerOn and
; ZTimerOff calls, the timer turns over and the count is
; inaccurate. When this happens, an error message is displayed
; instead of a count. The long-period Zen timer should be used
; in such cases.
;
; Note: Interrupts *MUST* be left off between calls to ZTimerOn
; and ZTimerOff for accurate timing and for detection of
; timer overflow.
;
; Note: These routines can introduce slight inaccuracies into the
; system clock count for each code section timed even if
; timer 0 doesn't overflow. If timer 0 does overflow, the
; system clock can become slow by virtually any amount of
; time, since the system clock can't advance while the
; precison timer is timing. Consequently, it's a good idea
; to reboot at the end of each timing session. (The
; battery-backed clock, if any, is not affected by the Zen
; timer.)
;
; All registers, and all flags except the interrupt flag, are
; preserved by all routines. Interrupts are enabled and then disabled
; by ZTimerOn, and are restored by ZTimerOff to the state they were
; in when ZTimerOn was called.
;
Code segment word public 'CODE'
assume cs:Code, ds:nothing
public ZTimerOn, ZTimerOff, ZTimerReport
;
; Base address of the 8253 timer chip.
;
BASE_8253 equ 40h
;
; The address of the timer 0 count registers in the 8253.
;
TIMER_0_8253 equ BASE_8253 + 0
;
; The address of the mode register in the 8253.
;
MODE_8253 equ BASE_8253 + 3
;
; The address of Operation Command Word 3 in the 8259 Programmable
; Interrupt Controller (PIC) (write only, and writable only when
; bit 4 of the byte written to this address is 0 and bit 3 is 1).
;
OCW3 equ 20h
;
; The address of the Interrupt Request register in the 8259 PIC
; (read only, and readable only when bit 1 of OCW3 = 1 and bit 0
; of OCW3 = 0).
;
IRR equ 20h
;
; Macro to emulate a POPF instruction in order to fix the bug in some
; 80286 chips which allows interrupts to occur during a POPF even when
; interrupts remain disabled.
;
MPOPF macro
local p1, p2
jmp short p2
p1: iret ;jump to pushed address & pop flags
p2: push cs ;construct far return address to
call p1 ; the next instruction
endm
;
; Macro to delay briefly to ensure that enough time has elapsed
; between successive I/O accesses so that the device being accessed
; can respond to both accesses even on a very fast PC.
;
DELAY macro
jmp $+2
jmp $+2
jmp $+2
endm
OriginalFlags db ? ;storage for upper byte of
; FLAGS register when
; ZTimerOn called
TimedCount dw ? ;timer 0 count when the timer
; is stopped
ReferenceCount dw ? ;number of counts required to
; execute timer overhead code
OverflowFlag db ? ;used to indicate whether the
; timer overflowed during the
; timing interval
;
; String printed to report results.
;
OutputStr label byte
db 0dh, 0ah, 'Timed count: ', 5 dup (?)
ASCIICountEnd label byte
db ' microseconds', 0dh, 0ah
db '$'
;
; String printed to report timer overflow.
;
OverflowStr label byte
db 0dh, 0ah
db '****************************************************'
db 0dh, 0ah
db '* The timer overflowed, so the interval timed was *'
db 0dh, 0ah
db '* too long for the precision timer to measure. *'
db 0dh, 0ah
db '* Please perform the timing test again with the *'
db 0dh, 0ah
db '* long-period timer. *'
db 0dh, 0ah
db '****************************************************'
db 0dh, 0ah
db '$'
;********************************************************************
;* Routine called to start timing. *
;********************************************************************
ZTimerOn proc near
;
; Save the context of the program being timed.
;
push ax
pushf
pop ax ;get flags so we can keep
; interrupts off when leaving
; this routine
mov cs:[OriginalFlags],ah ;remember the state of the
; Interrupt flag
and ah,0fdh ;set pushed interrupt flag
; to 0
push ax
;
; Turn on interrupts, so the timer interrupt can occur if it's
; pending.
;
sti
;
; Set timer 0 of the 8253 to mode 2 (divide-by-N), to cause
; linear counting rather than count-by-two counting. Also
; leaves the 8253 waiting for the initial timer 0 count to
; be loaded.
;
mov al,00110100b ;mode 2
out MODE_8253,al
;
; Set the timer count to 0, so we know we won't get another
; timer interrupt right away.
; Note: this introduces an inaccuracy of up to 54 ms in the system
; clock count each time it is executed.
;
DELAY
sub al,al
out TIMER_0_8253,al ;lsb
DELAY
out TIMER_0_8253,al ;msb
;
; Wait before clearing interrupts to allow the interrupt generated
; when switching from mode 3 to mode 2 to be recognized. The delay
; must be at least 210 ns long to allow time for that interrupt to
; occur. Here, 10 jumps are used for the delay to ensure that the
; delay time will be more than long enough even on a very fast PC.
;
rept 10
jmp $+2
endm
;
; Disable interrupts to get an accurate count.
;
cli
;
; Set the timer count to 0 again to start the timing interval.
;
mov al,00110100b ;set up to load initial
out MODE_8253,al ; timer count
DELAY
sub al,al
out TIMER_0_8253,al ;load count lsb
DELAY
out TIMER_0_8253,al ;load count msb
;
; Restore the context and return.
;
MPOPF ;keeps interrupts off
pop ax
ret
ZTimerOn endp
;********************************************************************
;* Routine called to stop timing and get count. *
;********************************************************************
ZTimerOff proc near
;
; Save the context of the program being timed.
;
push ax
push cx
pushf
;
; Latch the count.
;
mov al,00000000b ;latch timer 0
out MODE_8253,al
;
; See if the timer has overflowed by checking the 8259 for a pending
; timer interrupt.
;
mov al,00001010b ;OCW3, set up to read
out OCW3,al ; Interrupt Request register
DELAY
in al,IRR ;read Interrupt Request
; register
and al,1 ;set AL to 1 if IRQ0 (the
; timer interrupt) is pending
mov cs:[OverflowFlag],al ;store the timer overflow
; status
;
; Allow interrupts to happen again.
;
sti
;
; Read out the count we latched earlier.
;
in al,TIMER_0_8253 ;least significant byte
DELAY
mov ah,al
in al,TIMER_0_8253 ;most significant byte
xchg ah,al
neg ax ;convert from countdown
; remaining to elapsed
; count
mov cs:[TimedCount],ax
; Time a zero-length code fragment, to get a reference for how
; much overhead this routine has. Time it 16 times and average it,
; for accuracy, rounding the result.
;
mov cs:[ReferenceCount],0
mov cx,16
cli ;interrupts off to allow a
; precise reference count
RefLoop:
call ReferenceZTimerOn
call ReferenceZTimerOff
loop RefLoop
sti
add cs:[ReferenceCount],8 ;total + (0.5 * 16)
mov cl,4
shr cs:[ReferenceCount],cl ;(total) / 16 + 0.5
;
; Restore original interrupt state.
;
pop ax ;retrieve flags when called
mov ch,cs:[OriginalFlags] ;get back the original upper
; byte of the FLAGS register
and ch,not 0fdh ;only care about original
; interrupt flag...
and ah,0fdh ;...keep all other flags in
; their current condition
or ah,ch ;make flags word with original
; interrupt flag
push ax ;prepare flags to be popped
;
; Restore the context of the program being timed and return to it.
;
MPOPF ;restore the flags with the
; original interrupt state
pop cx
pop ax
ret
ZTimerOff endp
;
; Called by ZTimerOff to start timer for overhead measurements.
;
ReferenceZTimerOn proc near
;
; Save the context of the program being timed.
;
push ax
pushf ;interrupts are already off
;
; Set timer 0 of the 8253 to mode 2 (divide-by-N), to cause
; linear counting rather than count-by-two counting.
;
mov al,00110100b ;set up to load
out MODE_8253,al ; initial timer count
DELAY
;
; Set the timer count to 0.
;
sub al,al
out TIMER_0_8253,al ;load count lsb
DELAY
out TIMER_0_8253,al ;load count msb
;
; Restore the context of the program being timed and return to it.
;
MPOPF
pop ax
ret
ReferenceZTimerOn endp
;
; Called by ZTimerOff to stop timer and add result to ReferenceCount
; for overhead measurements.
;
ReferenceZTimerOff proc near
;
; Save the context of the program being timed.
;
push ax
push cx
pushf
;
; Latch the count and read it.
;
mov al,00000000b ;latch timer 0
out MODE_8253,al
DELAY
in al,TIMER_0_8253 ;lsb
DELAY
mov ah,al
in al,TIMER_0_8253 ;msb
xchg ah,al
neg ax ;convert from countdown
; remaining to amount
; counted down
add cs:[ReferenceCount],ax
;
; Restore the context of the program being timed and return to it.
;
MPOPF
pop cx
pop ax
ret
ReferenceZTimerOff endp
;********************************************************************
;* Routine called to report timing results. *
;********************************************************************
ZTimerReport proc near
pushf
push ax
push bx
push cx
push dx
push si
push ds
;
push cs ;DOS functions require that DS point
pop ds ; to text to be displayed on the screen
assume ds:Code
;
; Check for timer 0 overflow.
;
cmp [OverflowFlag],0
jz PrintGoodCount
mov dx,offset OverflowStr
mov ah,9
int 21h
jmp short EndZTimerReport
;
; Convert net count to decimal ASCII in microseconds.
;
PrintGoodCount:
mov ax,[TimedCount]
sub ax,[ReferenceCount]
mov si,offset ASCIICountEnd - 1
;
; Convert count to microseconds by multiplying by .8381.
;
mov dx,8381
mul dx
mov bx,10000
div bx ;* .8381 = * 8381 / 10000
;
; Convert time in microseconds to 5 decimal ASCII digits.
;
mov bx,10
mov cx,5
CTSLoop:
sub dx,dx
div bx
add dl,'0'
mov [si],dl
dec si
loop CTSLoop
;
; Print the results.
;
mov ah,9
mov dx,offset OutputStr
int 21h
;
EndZTimerReport:
pop ds
pop si
pop dx
pop cx
pop bx
pop ax
MPOPF
ret
ZTimerReport endp
Code ends
end
Я добавил nasm.exe в свой путь, сохранил этот файл как listing1.asm и попытался использовать следующую команду CMD для его сборки:
nasm -f win32 listing1.asm
Однако он не собрался и вместо этого выдал следующие ошибки:
listing1.asm:50: error: parser: instruction expected
listing1.asm:51: error: parser: instruction expected
listing1.asm:82: error: parser: instruction expected
listing1.asm:83: error: parser: instruction expected
listing1.asm:95: error: parser: instruction expected
listing1.asm:99: error: symbol `endm' redefined
listing1.asm:114: error: parser: instruction expected
listing1.asm:115: error: comma expected after operand 4
listing1.asm:116: error: parser: instruction expected
listing1.asm:122: error: parser: instruction expected
listing1.asm:142: error: parser: instruction expected
listing1.asm:176: error: symbol `DELAY' redefined
listing1.asm:179: error: symbol `DELAY' redefined
listing1.asm:188: error: parser: instruction expected
listing1.asm:190: error: symbol `endm' redefined
listing1.asm:200: error: symbol `DELAY' redefined
listing1.asm:203: error: symbol `DELAY' redefined
listing1.asm:208: error: symbol `MPOPF' redefined
listing1.asm:212: error: symbol `ZTimerOn' redefined
listing1.asm:212: error: parser: instruction expected
listing1.asm:218: error: parser: instruction expected
listing1.asm:237: error: symbol `DELAY' redefined
listing1.asm:252: error: symbol `DELAY' redefined
listing1.asm:282: error: comma, colon or end of line expected
listing1.asm:292: error: symbol `MPOPF' redefined
listing1.asm:298: error: symbol `ZTimerOff' redefined
listing1.asm:298: error: parser: instruction expected
listing1.asm:304: error: parser: instruction expected
listing1.asm:316: error: symbol `DELAY' redefined
listing1.asm:322: error: symbol `DELAY' redefined
listing1.asm:327: error: symbol `MPOPF' redefined
listing1.asm:331: error: symbol `ReferenceZTimerOn' redefined
listing1.asm:331: error: parser: instruction expected
listing1.asm:338: error: parser: instruction expected
listing1.asm:350: error: symbol `DELAY' redefined
listing1.asm:352: error: symbol `DELAY' redefined
listing1.asm:363: error: symbol `MPOPF' redefined
listing1.asm:368: error: symbol `ReferenceZTimerOff' redefined
listing1.asm:368: error: parser: instruction expected
listing1.asm:374: error: parser: instruction expected
listing1.asm:386: error: symbol `assume' redefined
listing1.asm:386: error: parser: instruction expected
listing1.asm:392: error: comma, colon or end of line expected
listing1.asm:402: error: comma, colon or end of line expected
listing1.asm:426: error: comma, colon or end of line expected
listing1.asm:436: error: symbol `MPOPF' redefined
listing1.asm:439: error: symbol `ZTimerReport' redefined
listing1.asm:439: error: parser: instruction expected
listing1.asm:441: error: symbol `Code' redefined
listing1.asm:441: error: parser: instruction expected
Не знаю, что мне здесь делать; Я пытался немного погуглить, но ничего не придумал. Кто-нибудь признает эти ошибки?
- Печать
Страницы: [1] Вниз
Тема: nasm (Прочитано 3497 раз)
0 Пользователей и 1 Гость просматривают эту тему.
Yot
Не транслируется программа
%include "stud_io.inc"
Помогите разобраться кто программирует на NASM
global _start
section .text
_start: mov eax,0
again:PRINT "Hello"
PUTCHAR 10
inc eax
cmp eax,5
jl again
FINISH
hello5.asm:5: error: parser: instruction expected
hello5.asm:6: error: parser: instruction expected
inkblack
А разве в
NASMe
есть инструкция
again:PRINT
Не надо ли там пробел поставить?
Делюсь знаниями, но их у меня мало!
user78
«stud_io.inc» и исполняемый файл в одной папке лежат?
Запускаете пример из папки с исполняемым файлом (инструменты—>открыть текущую папку в терминале)?
Мне тоже книга Столярова нравится больше, чем у других авторов.
Yot
«stud_io.inc» и исполняемый файл в одной папке лежат?
файл с макросами я поместил в каталог usr/bin а исполняемый файл в домашней папке.
user78
Цитата с сайта Столярова:
Чтобы всё сработало, этот файл (с макросами) должен находиться в той же директории, что и ваш файл (исполняемый), который вы транслируете nasm’ом. Вообще-то это довольно очевидно, если внимательно прочитать в книге, как работает макродиректива %include.
Yot
Сделал так как вы посоветовали и всё равно две ошибки в 5 и 6 строчках.
Я думаю тут что-то с синтаксисом не в порядке,ведь с макросом FINISH не было проблем даже когда файл с макросами находился в папке usr/bin.
user78
Что-то без понятия, я, ведь, тоже новичок. У меня такое подозрение, что прога не видит «stud_io.inc».
Просто напишу как я делал этот пример:
Создал папку для примеров. В ней написал этот пример. В эту же папку поместил файл»stud_io.inc». У меня файловый менеджер PCManFM. Зашёл в папку с примером, на верхней панели PCManFM нажимаю инструменты—>открыть текущую папку в терминале. Открывается терминал, и в нём компилирую и запускаю пример.
ArcFi
В своё время тоже пришлось ковыряться — переписал на GAS (GNU Assembler), и всё заработало. =)
SergeyIT
Извините, я все еще учусь
Yot
1. Это учли?
Естественно учел,только безрезультатно.
Вобщем убираю макросы PRINT «Hello» и PUTCHAR 10 пишу что-нибудь вроде
mov eax,10
программа транслируется.Макрос FINISH остается с ним проблем нету.Даже самому интересно в чем дело,ну не в шляпе же.
add eax,5
SergeyIT
ubuntu 12.04.3 32бит
NASM version 2.09.10 compiled on Oct 17 2011
a.asm
stud-io.inc
~/temp/asm/1$ nasm -f elf a.asm
~/temp/asm/1$ ld -s -o a a.o
~/temp/asm/1$ ./a
Hello
Hello
Hello
Hello
Hello
~/temp/asm/1$
Что я делаю не так?
Извините, я все еще учусь
Yot
С вашим файлом stud_io.inc программа заработала,видимо я что-то пропустил в своем файле,хотя проверял его два раза.
Спасибо SergeyIT.
SergeyIT
Yot,
Не за что. И это не мой файл — это «моя» первая программа на асме для РС
Извините, я все еще учусь
- Печать
Страницы: [1] Вверх
Здравствуйте, я только начинаю изучать ассемблер. Есть код программы, пытаюсь его скомпилировать:
Код программы
.model tiny
.286
.data
msg db 'Hello World11111111111111111111111111111111111111111111111111111111'
position word 0312h
color db 03dh
count word 0043h
.code
org 100h
start:
call clrscr
mov ax, 0 ;word
mov ax, 1300h
mov bp, offset msg
mov cx, count
mov dx, position
mov bl, color
int 10h
mov ah, 02h
mov dx, position
sub dx, 0101h
int 10h
mov ah, 09h
mov al, 0c9h
mov cx, 1
int 10h
mov ah, 02h
inc dx
int 10h
mov ah, 09h
mov al, 0cdh
mov cx, count
int 10h
add dx, count
mov ah, 02h
int 10h
mov ah, 09h
mov al, 0bbh
mov cx, 1
int 10h
mov ah, 02h
add dx, 0100h
int 10h
mov ah, 09h
mov al, 0bah
mov cx, 1
int 10h
mov ah, 02h
sub dx, count
dec dx
int 10h
mov ah, 09h
int 10h
mov ah, 02h
add dx, 0100h
int 10h
mov ah, 09h
mov al, 0c8h
int 10h
mov ah, 02h
inc dx
int 10h
mov ah, 09h
mov al, 0cdh
mov cx, count
int 10h
mov ah, 02h
add dx, count
int 10h
mov ah, 09h
mov al, 0bch
mov cx, 01h
int 10h
mov ah, 02h
mov dx, 1801h
int 10h
int 20h
clrscr:
mov ah, 0h
mov al, 03h
int 10h
ret
end start
Компилирую командой: nasm -f bin first.asm -o first.com
Получаю следующие ошибки:
D:Assembler>nasm -f bin first.asm -o first.com
first.asm:1: error: attempt to define a local label before any non-local labels
first.asm:1: error: parser: instruction expected
first.asm:2: warning: label alone on a line without a colon might be in error [-w+orphan-labels]
first.asm:2: error: attempt to define a local label before any non-local labels
first.asm:3: warning: label alone on a line without a colon might be in error [-w+orphan-labels]
first.asm:3: error: attempt to define a local label before any non-local labels
first.asm:5: error: parser: instruction expected
first.asm:7: error: parser: instruction expected
first.asm:8: warning: label alone on a line without a colon might be in error [-w+orphan-labels]
first.asm:16: error: comma, colon, decorator or end of line expected after operand
first.asm:95: error: parser: instruction expected
Мои знакомые просто как-то переносят этот код в DoxBOX и там у них всё прекрасно работает. Подскажите пожалуйста как можно исправить код программы, чтобы он правильно компилировался NASM-ом. Спасибо.
Assembly Online Compiler
Write, Run & Share Assembly code online using OneCompiler’s Assembly online compiler for free. It’s one of the robust, feature-rich online compilers for Assembly language. Getting started with the OneCompiler’s Assembly compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as Assembly
and start coding.
About Assembly
Assembly language(asm) is a low-level programming language, where the language instructions will be more similar to machine code instructions.
Every assembler may have it’s own assembly language designed for a specific computers or an operating system.
Assembly language requires less execution time and memory. It is more helful for direct hardware manipulation, real-time critical applications. It is used in device drivers, low-level embedded systems etc.
Syntax help
Assembly language usually consists of three sections,
-
Data section
To initialize variables and constants, buffer size these values doesn’t change at runtime.
-
bss section
To declare variables
-
text section
_start
specifies the starting of this section where the actually code is written.
Variables
There are various define directives to allocate space for variables for both initialized and uninitialized data.
1. To allocate storage space to Initialized data
Syntax
variable-name define-directive initial-value
Define Directive | Description | Allocated Space |
---|---|---|
DB | Define Byte | 1 byte |
DW | Define Word | 2 bytes |
DD | Define Doubleword | 4 bytes |
DQ | Define Quadword | 8 bytes |
DT | Define Ten Bytes | 10 bytes |
2. To allocate storage space to un-initialized data
Define Directive | Description |
---|---|
RESB | Reserve a Byte |
RESW | Reserve a Word |
RESD | Reserve a Doubleword |
RESQ | Reserve a Quadword |
REST | Reserve a Ten Bytes |
Constants
Constants can be defined using
1. equ
- To define numeric constants
CONSTANT_NAME EQU regular-exp or value
2. %assign
- To define numeric constants.
%assign constant_name value
3. %define
- To define numeric or string constants.
%define constant_name value
Loops
Loops are used to iterate a set of statements for a specific number of times.
mov ECX,n
L1:
;<loop body>
loop L1
where n specifies the no of times loops should iterate.
Procedures
Procedure is a sub-routine which contains set of statements. Usually procedures are written when multiple calls are required to same set of statements which increases re-usuability and modularity.
procedure_name:
;procedure body
ret
6 Years Ago
;I am using:
;gcc (Ubuntu 4.9.3-8ubuntu2~14.04) 4.9.3
;g++ (Ubuntu 4.9.3-8ubuntu2~14.04) 4.9.3
;I keep getting the following error:
;ch4p5.s:13: error: parser: instruction expected
;ch4p5.s:15: error: parser: instruction expected
;How do I fix it?
;Here is what I have:
%include "macros_windows64.s"
.MODEL SMALL
.STACK 100H
@DATA:
PROMPT_1 db 'Enter the hexadecimal number ( max 4-digit ) : $'
PROMPT_2 db 0DH,0AH,'The equivalent 16-bit binary number is : $'
ILLEGAL db 0DH,0AH,'Illegal hex number. Try again : $'
COUNT db ?
.CODE
.STARTUP
MAIN_PROC:
MOV AX, @DATA ; initialize DS
MOV DS, AX
LEA DX, [PROMPT_1] ; load and display the string PROMPT_1
MOV AH,9
INT 21H
JMP @START ; jump to label @START_2
@START_1: ; jump label
LEA DX, [ILLEGAL] ; load and display the string ILLEGAL
MOV AH, 9
INT 21H
@START: ;
XOR BX,BX ; clear BX
MOV [COUNT],30H ; initialize loop counter
@START_2: ; jump label
MOV AH, 1 ; set input function
INT 21H ; read a character
CMP AL, 0DH ; compare Al with CR
JNE @SKIP ; jump to label @SKIP if AL!=CR
CMP [COUNT],30H ; compare COUNT with 0
JBE @START_1 ; jump to label @START_1 if COUNT<=0
JMP @END ; jump to label @END
@SKIP: ; jump label
CMP AL, "A" ; compare AL with "A"
JB @DECIMAL ; jump to label @DECIMAL if AL<A
CMP AL, "F" ; compare AL with "F"
JA @START_1 ; jump to label @START_1 if AL>F
ADD AL, 09H ; add 9 to AL
JMP @OK ; jump to label @OK
@DECIMAL: ; jump label
CMP AL, 30H ; compare AL with 0
JB @START_1 ; jump to label @START_1 if AL<0
CMP AL, 39H ; compare AL with 9
JA @START_1 ; jump to label @START_1 if AL>9
@OK: ; jump label
INC [COUNT] ; increment the COUNT variable
AND AL, 0FH ; convert the ascii into binary code
MOV CL, 4 ; set CL=4
SHL AL, CL ; shift AL towards left by 4 positions
MOV CX, 4 ; set CX=4
@LOOP_1: ; loop label
SHL AL, 1 ; shift AL towards left by 1 position
RCL BX, 1 ; rotate BX towards left by 1 position
; through carry
LOOP @LOOP_1 ; jump to label @LOOP_1 if CX!=0
CMP [COUNT], 34H ; compare COUNT with 4
JE @END ; jump to label @END if COUNT=4
JMP @START_2 ; jump to label @START_2
@END: ; jump label
LEA DX, [PROMPT_2] ; load and display the string PROMPT_2
MOV AH, 9
INT 21H
MOV CX, 16 ; set CX=16
MOV AH, 2 ; set output function
@LOOP_2: ; loop label
SHL BX, 1 ; shift BX towards left by 1 position
JC @ONE ; jump to label @ONE if CF=1
MOV DL,30H ; set DL=0
JMP @DISPLAY ; jump to label @DISPLAY
@ONE: ; jump label
MOV DL, 31H ; set DL=1
@DISPLAY: ; jump label
INT 21H ; display a character
LOOP @LOOP_2 ; jump to label @LOOP_2 if CX!=0
MOV AH, 4CH ; return control
INT 21H
done:
.EXIT
Recommended Answers
It’s a shame you pasted this way. Otherwise I would have headed to those lines and took a closer look. Since the line numbers are off it’s harder. Try pasting the code so that the line numbers match your assembler errors.
Jump to Post
All 3 Replies
rproffitt
2,382
«Nothing to see here.»
Moderator
6 Years Ago
It’s a shame you pasted this way. Otherwise I would have headed to those lines and took a closer look. Since the line numbers are off it’s harder. Try pasting the code so that the line numbers match your assembler errors.
Edited
6 Years Ago
by rproffitt because:
Typo correction.
6 Years Ago
It would be lines 17 and 19 on here.
rproffitt
2,382
«Nothing to see here.»
Moderator
6 Years Ago
This looks like assembly code, not GCC. Try gasm? Or is there more to this story like you want some x86 assember?
Edited
6 Years Ago
by rproffitt because:
Typo correction.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.