Random Numbers in Assembly Language
; Assembly Language implementation of random number generation
section .data
fmt_int db "%d,", 0
fmt_int_nl db "%d", 10, 0
fmt_float db "%f", 10, 0
fmt_float2 db "%f,%f", 10, 0
section .text
global main
extern printf
extern rand
main:
push rbp
mov rbp, rsp
; Generate random integers (0-99)
call rand
xor edx, edx
mov ecx, 100
div ecx
mov esi, edx
mov edi, fmt_int
xor eax, eax
call printf
call rand
xor edx, edx
mov ecx, 100
div ecx
mov esi, edx
mov edi, fmt_int_nl
xor eax, eax
call printf
; Generate random float (0.0-1.0)
call rand
cvtsi2ss xmm0, eax
divss xmm0, [rel const_rand_max]
mov edi, fmt_float
mov eax, 1
call printf
; Generate random floats (5.0-10.0)
call rand
cvtsi2ss xmm0, eax
divss xmm0, [rel const_rand_max]
mulss xmm0, [rel const_five]
addss xmm0, [rel const_five]
call rand
cvtsi2ss xmm1, eax
divss xmm1, [rel const_rand_max]
mulss xmm1, [rel const_five]
addss xmm1, [rel const_five]
mov edi, fmt_float2
mov eax, 2
call printf
pop rbp
xor eax, eax
ret
section .rodata
const_rand_max: dd 2147483647.0 ; RAND_MAX
const_five: dd 5.0
This Assembly Language code demonstrates the generation of random numbers, similar to the original example. Here’s an explanation of the key parts:
We define format strings for printing integers and floats.
The
main
function is our entry point.To generate random integers between 0 and 99:
- We call the
rand
function. - We use the
div
instruction to get the remainder when divided by 100. - We print the result using
printf
.
- We call the
To generate a random float between 0.0 and 1.0:
- We call
rand
and convert the result to a float. - We divide by
RAND_MAX
to get a value between 0 and 1. - We print the result using
printf
.
- We call
To generate random floats between 5.0 and 10.0:
- We follow a similar process as above.
- We multiply the result by 5 and add 5 to shift the range.
- We generate two such numbers and print them.
Note that this implementation uses the C standard library’s rand()
function, which may not provide the same level of randomness as Go’s math/rand/v2
package. In a real-world scenario, you might want to use a more sophisticated random number generator.
Also, Assembly Language doesn’t have built-in support for floating-point operations in the same way high-level languages do. We’re using SSE (Streaming SIMD Extensions) instructions for floating-point arithmetic here.
To run this program, you would need to assemble it, link it with the C standard library, and then execute the resulting binary. The exact commands would depend on your operating system and assembler.