summaryrefslogtreecommitdiff
path: root/minilib/stdlib.c
blob: b6499a4ebc8f5295436cdc419ef70afdcac42048 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "stdlib.h"
#include "stdbool.h"
#include "string.h"
#include "stddef.h"

static void strreverse( char *s )
{
	char *end = s + strlen( s ) - 1;
	
	while( s < end ) {
		/* XOR swap; */
		*s ^= *end;
		*end ^= *s;
		*s ^= *end;
		s++;
		end--;
	}
}
    
char *itoa( int v, char *s, int base )
{
	static char digit[] = "0123456789ABCDEF";
	bool sign = false;
	char *p = s;
	
	if( base < 2 || base > 16 ) {
		return NULL;
	}
	
	if( v < 0 ) {
		v = -v;
		sign = true;
	} 
	
	do {
		*p++ = digit[v % base];
	} while( ( v /= base ) > 0 );

	if( sign ) {
		*p++ = '-';
	}
	*p = '\0';
	
	strreverse( s );
	
	return s;
}

/* TODO: this is the Linux hosted environment */
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>

void exit( int status )
{
	syscall( __NR_exit, status );
}