Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created January 19, 2025 03:38
Show Gist options
  • Save thinkphp/0f02a743dd976261c561eefa9abcc09b to your computer and use it in GitHub Desktop.
Save thinkphp/0f02a743dd976261c561eefa9abcc09b to your computer and use it in GitHub Desktop.
Fragment de program: determina valoarea absoluta intreaga |v| = sqrt(v1^2 + v2^2 + ... + v3^2) a unui vector V intr-un spatiu n-dimensional. Respecta conventiile IA-32
section .data
prompt_n db "Vector intr-un spatiul n-dimensional (n): ", 0
prompt_num db "Enter number %d: ", 10, 0
result_msg db "Sum of squares is: %ld", 10, 0
sqrt_msg db "Square root of sum is: %lf", 10, 0
fmt_int db "%ld%*c", 0
section .bss
n resq 1
current_num resq 1
sum resq 1
section .text
global main
extern printf
extern scanf
extern sqrt ; Changed back to just sqrt
main:
; Setup stack frame
push rbp
mov rbp, rsp
sub rsp, 32
; Initialize sum to 0
mov qword [sum], 0
; Save registers that we'll use
push rbx
push r12
; Prompt for n
lea rdi, [prompt_n]
xor eax, eax
call printf
; Read n
lea rdi, [fmt_int]
mov rsi, n
xor eax, eax
call scanf
; Check if scanf was successful
cmp eax, 1
jne exit_program
; Initialize loop counter
mov r12, [n]
read_loop:
; Check if counter is zero
test r12, r12
jz calculate_sqrt
; Print prompt for current number
lea rdi, [prompt_num]
mov rsi, r12
xor eax, eax
call printf
; Read number
lea rdi, [fmt_int]
mov rsi, current_num
xor eax, eax
call scanf
; Check if scanf was successful
cmp eax, 1
jne exit_program
; Calculate square and add to sum
mov rax, [current_num]
imul rax, rax
add [sum], rax
; Decrement counter
dec r12
jmp read_loop
calculate_sqrt:
; Print sum of squares
lea rdi, [result_msg]
mov rsi, [sum]
xor eax, eax
call printf
; Convert sum to double and calculate square root
pxor xmm0, xmm0 ; Clear xmm0
cvtsi2sd xmm0, qword [sum] ; Convert integer to double
movsd xmm0, xmm0 ; Ensure value is in xmm0
sub rsp, 8 ; Align stack for call
call sqrt ; Calculate square root (result in xmm0)
add rsp, 8 ; Restore stack
; Print square root
lea rdi, [sqrt_msg]
mov eax, 1 ; One floating point argument
call printf
exit_program:
; Restore saved registers
pop r12
pop rbx
; Cleanup stack and return
leave
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment