Computing Hamming Distance in x86 assembly
; assignment1.asm
; Calculates the Hamming distance between two strings given by the user
;
; Assemble command:
; nasm -f elf assignment1.asm
; Link command:
; gcc -m32 -o assignment1 assignment1.o
; Run command:
; ./assignment1
;
SECTION .data
prompt1: db "Please enter the first string: ",10
len1: equ $-prompt1
prompt2: db "Please enter the second string: ",10
len2: equ $-prompt2
result: db "The Hamming distance between the strings is:",10,"%d",10,0
string1: times(256) db 0 ; space to save first string
string2: times(256) db 0 ; space to save second string
SECTION .text
extern printf
;-----------------
; Main function
;-----------------
global main
main:
push ebp ; set up stack frame
mov ebp,esp
mov eax,4 ; use the write function
mov ebx,1 ; use the standard output
mov edx,len1 ; set the number of characters to print
mov ecx,prompt1 ; string to print
int 0x80 ; call kernel to print the message
mov eax,3 ; use the read function
mov ebx,0 ; use the standard input
mov ecx,string1 ; load in string1
mov edx,255 ; read at most 255 characters
int 0x80 ; call kernel to read the string
mov BYTE [string1 + eax -1], 0 ; insert string terminator
mov eax,4 ; use the write function
mov ebx,1 ; use the standard output
mov edx,len2 ; set the number of characters to print
mov ecx,prompt2 ; string to print
int 80h ; call kernel to print the message
mov eax,3 ; use the read function
mov ebx,0 ; use the standard input
mov ecx,string2 ; load in string2
mov edx,255 ; read at most 255 characters
int 0x80 ; call kernel to read the string
mov BYTE [string2 + eax -1], 0 ; insert string terminator
mov esi, string1; point to first string with esi
mov edi, string2; point to second string with edi
mov ecx, 0; ecx will have the hamming distance
cmploop:
mov al, BYTE [esi]; get a byte from both strings
mov ah, BYTE [edi]
cmp al, 0; if the first string is shorter, end comparison
je endcmp
cmp ah, 0; if the second string is shorter, end comparison
je endcmp
xor al, ah; compare both bytes
bitloop: loop to count bits in comparison
; (hamming distance between bytes)
cmp al, 0; if there are no more bits in 1, end count
je endbitloop
shr al, 1; move the lowest bit to the carry
jnc bitloop ; if it's zero, continue
inc ecx ; else, increment distance
jmp bitloop
endbitloop:
inc esi ; advance to next byte in both strings
inc edi
jmp cmploop
endcmp:
push ecx; put hamming distance in stack
push result; put format string in stack
call printf; call printf to print result
add esp, 8; restore stack pointer
mov esp,ebp ; takedown stack frame
pop ebp
mov eax,0 ; normal, no error, return value
ret ; return