Generating a random number within range of 0-9 in x86 8086 Assembly -
first of all, new 8086 assembly , has been pretty difficult me grab knowledge. nevertheless, i'll best.
i have been trying write code generate random number within range of 0-9. after looking several examples , suggestion, ended with. did not apply mathematical function on retrieved clock count, simplicity , thought unnecessary. ended with, reasons, generating number 6,7 fewer times numbers such 1,3 , 9. believe because i'm taking lower order of clock ticks, values change rapidly.
my purpose simulate dice roll later ill change range of below codes 1-6. question is, adequate enough purpose? or there better way this?
codes:
randgen: ; generate rand no using system time randstart: mov ah, 00h ; interrupts system time int 1ah ; cx:dx hold number of clock ticks since midnight ; lets take lower bits of dl start.. mov bh, 57 ; set limit 57 (ascii 9) mov ah, dl cmp ah, bh ; compare value in dl, ja randstart ; if more, regenerate. if not, continue... mov bh, 49 ; set limit 48 (ascii 0) mov ah, dl cmp ah, bh ; compare value in dl jb randstart ; if less, regenerate. ; if not, need mov ah, 2h ; call interrupt display value in dl int 21h ret
answer, @johnfound:
i found way simpler, , takes less time generate random number. mentioned works if need 1 single random numbers, or interval between random numbers includes pauses human input. if not, numbers not random @ (i believe due time seed take doesn't change). fine case, since simulating roll dice, , need user intervention (another roll) before running code again.
randgen: ; generate rand no using system time randstart: mov ah, 00h ; interrupts system time int 1ah ; cx:dx hold number of clock ticks since midnight mov ax, dx xor dx, dx mov cx, 10 div cx ; here dx contains remainder of division - 0 9 add dl, '0' ; ascii '0' '9' mov ah, 2h ; call interrupt display value in dl int 21h ret
what did: 1.we moved value in dx ax 2.we cleared dx. 3.we moved 10 dec cx. 4.we divided ax cx hence remainder within 0-9 dec stored in dx 5.finally, added ascii '0' (dec 48) dx them ascii '0' '9'.
this trick works if need 1 single random numbers, or interval between random numbers includes pauses human input. in other cases, numbers not random @ all.
if need many random numbers, there different pseudo-random number algorithms available.
another note there more easy way number in needed interval:
mov ax, dx xor dx, dx mov cx, 10 div cx ; here dx contains remainder of division - 0 9 add dl, '0' ; ascii '0' '9'
you can use method every random number generator of course.
Comments
Post a Comment