Search code examples
assemblymasmirvine32

assembly convert number into character


I have this variable:

Message DB 10 dup(?)

I'm trying to generate 10 random characters and then save them into variable.

mov ecx,10
mov edi,0

GenerateString:
    mov eax,60h
    call RandomRange
    sub eax,27
    add al,'0'
    mov Message[edi],al

    inc edi
    loop GenerateString

mov edx,offset Message
call WriteString

I found somewhere that I have to substract number by 27 and add ascii 0, but it's not working properly. Please note I have to use RandomRange.


Solution

  • Irvine's RandomRange creates numbers in the range 0..EAX-1. With other words: You get a number within a range of a certain amount of different numbers. Since you want an ASCII character in the range a..z (97..122) you have

    • to determine the size of the range: 122-97+1 = 26 characters,
    • to move the range of RandomRange to the desired range by adding the start value: 97.

    BTW: You will always get the same sequence if you don't initialize RandomRange with Randomize.

    INCLUDE Irvine32.inc
    
    .DATA
        Message DB 10 dup(0)
    
    .CODE
    main PROC
    
        call Randomize                      ; Initialization for `RandomRange`
    
        mov ecx, LENGTHOF Message - 1       ; Without the terminating null!
        mov edi, 0
    
        GenerateString:
    
        mov eax, 26                         ; Range: [0..25] = 26 numbers
        call RandomRange
        add eax, 97                         ; Move the range from [0..25] to [97..122]
        mov Message[edi],al
    
        inc edi
        loop GenerateString
    
        mov edx,offset Message
        call WriteString
    
        exit
    
    main ENDP
    
    END main