본문 바로가기

Computer Science/Embedded System

[MIPS Assembly] random generator(난수 생성기)

반응형

다음 pseudo code를 기준으로 작성된 소스입니다.


Random Number Generators

m_w = <choose-initializer>;    /* must not be zero */

m_z = <choose-initializer>;    /* must not be zero */

 

uint get_random()

{

    m_z = 36969 * (m_z & 65535) + (m_z >> 16);

    m_w = 18000 * (m_w & 65535) + (m_w >> 16);

    return (m_z << 16) + m_w;  /* 32-bit result */

}




***함수 사용시 랜덤변수의 최대값을 parameter로 stack의 top에 넣어서 넘겨 주어야 합니다.***






.data

n1: .word 3 # random init value1

n2: .word 4 # random init value2

.text


# generate random value

# parameter : $a0 = maximum of random value

# return value : $v0 = (int)random value

random:

lw $a0, 0($sp)

addi         $sp, $sp, 4         # pop parameter $a0(max random value)

addi         $sp, $sp, -16                 # adjust stack for 4 item

sw $s0, 12($sp)         # save $s0

sw $s1, 8($sp) # save $s1

sw $s2, 4($sp) # save $s2

sw $s3, 0($sp) # save $s3


la $s2, n1

la $s3, n2


lw $s0, ($s2)

lw $s1, ($s3)


sra $s2, $s0, 16

andi         $s0, $s0, 65535

addiu         $s3, $zero, 32767

mult         $s3, $s0

mflo         $s0

add $s0, $s0, $s2

sra $s2, $s1, 16

andi     $s1, $s1, 65535

addiu     $s3, $zero, 18000

mult         $s3 $s1

mflo         $s1

addu         $s1, $s1, $s2


la $s2, n1

la $s3, n2

sw $s0, ($s2)

sw $s1, ($s3)


sll $s0, $s0, 16

addu $v0, $s0, $s1

andi $v0, $v0, 1023


random_L1:

bltu $v0, $a0, random_L1_exit # if($v0 < t0) goto decide_L1

sub $v0, $v0, $a0

b random_L1

random_L1_exit:


lw $s3, 0($sp) # restore saved $s3

lw $s2, 4($sp) # restore saved $s2

lw $s1, 8($sp) # restore saved $s1

lw $s0, 12($sp) # restore saved $s0

addi $sp, $sp, 16 # pop 4 item from stack

jr $ra # return






MIPS를 이용해서 거의 처음 짠 소스인데 INTEL계열 어셈블리가 쉽다는걸 느꼈습니다.

반응형