kern

annotate src/klibc/stdlib.c @ 53:23abbeea4d5f

llalallalala
author John Tsiombikas <nuclear@member.fsf.org>
date Mon, 08 Aug 2011 09:53:10 +0300
parents
children f83f50c17c3b
rev   line source
nuclear@6 1 #include <stdlib.h>
nuclear@6 2 #include <ctype.h>
nuclear@6 3
nuclear@6 4 int atoi(const char *str)
nuclear@6 5 {
nuclear@6 6 return atol(str);
nuclear@6 7 }
nuclear@6 8
nuclear@6 9 long atol(const char *str)
nuclear@6 10 {
nuclear@6 11 long acc = 0;
nuclear@6 12 int sign = 1;
nuclear@6 13
nuclear@6 14 while(isspace(*str)) str++;
nuclear@6 15
nuclear@6 16 if(*str == '+') {
nuclear@6 17 str++;
nuclear@6 18 } else if(*str == '-') {
nuclear@6 19 sign = -1;
nuclear@6 20 str++;
nuclear@6 21 }
nuclear@6 22
nuclear@6 23 while(*str && isdigit(*str)) {
nuclear@6 24 acc = acc * 10 + (*str - '0');
nuclear@6 25 str++;
nuclear@6 26 }
nuclear@6 27
nuclear@6 28 return sign > 0 ? acc : -acc;
nuclear@6 29 }
nuclear@6 30
nuclear@6 31 void itoa(int val, char *buf, int base)
nuclear@6 32 {
nuclear@6 33 static char rbuf[16];
nuclear@6 34 char *ptr = rbuf;
nuclear@6 35 int neg = 0;
nuclear@6 36
nuclear@6 37 if(val < 0) {
nuclear@6 38 neg = 1;
nuclear@6 39 val = -val;
nuclear@6 40 }
nuclear@6 41
nuclear@6 42 if(val == 0) {
nuclear@6 43 *ptr++ = '0';
nuclear@6 44 }
nuclear@6 45
nuclear@6 46 while(val) {
nuclear@6 47 int digit = val % base;
nuclear@6 48 *ptr++ = digit < 10 ? (digit + '0') : (digit - 10 + 'a');
nuclear@6 49 val /= base;
nuclear@6 50 }
nuclear@6 51
nuclear@6 52 if(neg) {
nuclear@6 53 *ptr++ = '-';
nuclear@6 54 }
nuclear@6 55
nuclear@6 56 ptr--;
nuclear@6 57
nuclear@6 58 while(ptr >= rbuf) {
nuclear@6 59 *buf++ = *ptr--;
nuclear@6 60 }
nuclear@6 61 *buf = 0;
nuclear@6 62 }
nuclear@6 63
nuclear@6 64 void utoa(unsigned int val, char *buf, int base)
nuclear@6 65 {
nuclear@6 66 static char rbuf[16];
nuclear@6 67 char *ptr = rbuf;
nuclear@6 68
nuclear@6 69 if(val == 0) {
nuclear@6 70 *ptr++ = '0';
nuclear@6 71 }
nuclear@6 72
nuclear@6 73 while(val) {
nuclear@6 74 unsigned int digit = val % base;
nuclear@6 75 *ptr++ = digit < 10 ? (digit + '0') : (digit - 10 + 'a');
nuclear@6 76 val /= base;
nuclear@6 77 }
nuclear@6 78
nuclear@6 79 ptr--;
nuclear@6 80
nuclear@6 81 while(ptr >= rbuf) {
nuclear@6 82 *buf++ = *ptr--;
nuclear@6 83 }
nuclear@6 84 *buf = 0;
nuclear@6 85 }
nuclear@6 86