Collatz Muster

Reading time ~2 minutes

Collatz Framework in C

#include <stdio.h>
#include <stdlib.h>

extern int collatz  (int);
	   int collatz_c(int);
       void printme  (int);


int main(int argc, char* argv[])
{
	int x = atoi(argv[1]);
	int coll_c   = collatz_c(x);
	int coll_asm = collatz(x);
	int i;

	printme(coll_c);
	printme(coll_asm);
	return 0;
}

int collatz_c(int x)
{
	int i = 0;
	while (x > 1)
	{
		i++;
		if (x % 2 == 0)
		{
			x = x / 2;
		}
		else
		{
			x = x * 3;
			x++;
		}
	}
	return i;
}

void printme(int x)
{
	printf("%d\n", x);
}

Collatz in NASM

Ein Beispiel für direkte Übersetzung aus dem C-Code.

section .data
section .text

global collatz
collatz:
		;STACK SAVE
		push rbp
		push rbx
		push r12
		push r13

		;CREATE STACKFRAME
		mov  rbp, rsp

		;START CODE
		mov  rax, rdi     ; x: rax
		xor  r8 , r8      ; i: r8 = 0
		xor  r12, r12
		mov  r9 , 1       ; r9 : 1
		cmp  rax, r9
		jg   go_while
		mov  rax, r8
		jng  exit

go_while:
		inc  r8           ; i++
		mov  r10, 2       ; r10: 2
		mov  rdx, 0
		mov  r13, rax
		idiv r10
		cmp  rdx, r12
		je   go_if
		mov  rax, r13
		jne  go_else

go_if:
		mov  rax, rax
		cmp  rax, r9
		jg   go_while
		jng  exit

go_else:
		mov  r11, 3       ; r11: 3
		imul r11
		inc  rax
		cmp  rax, r9
		jg   go_while
		jng  exit

exit:
		mov  rax, r8      ; rax: i

		;STACK LOAD
		pop  r13
		pop  r12
		pop  rbx
		pop  rbp
		ret