98 lines
1.8 KiB
C
98 lines
1.8 KiB
C
/*
|
|
* libc.c
|
|
*
|
|
* Created on: Oct 11, 2018
|
|
* Author: rick
|
|
*/
|
|
|
|
#include "libc.h"
|
|
|
|
int memcpy(char *dst, char *src, int amount) {
|
|
for (int i = 0; i < amount; i++) {
|
|
dst[i] = src[i];
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int memset(char *dst, char data, int amount) {
|
|
for (int i = 0; i < amount; ++i) {
|
|
dst[i] = data;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int abs(int val) {
|
|
if (val >= 0) {
|
|
return val;
|
|
}
|
|
return val * -1;
|
|
}
|
|
|
|
// next stolen form https://www.techiedelight.com/implement-itoa-function-in-c/
|
|
// inline function to swap two numbers
|
|
void swap(char *x, char *y) {
|
|
char t = *x; *x = *y; *y = t;
|
|
}
|
|
|
|
// function to reverse buffer[i..j]
|
|
char* reverse(char *buffer, int i, int j)
|
|
{
|
|
while (i < j)
|
|
swap(&buffer[i++], &buffer[j--]);
|
|
|
|
return buffer;
|
|
}
|
|
|
|
// Iterative function to implement itoa() function in C
|
|
char* itoa(int value, char* buffer, int base)
|
|
{
|
|
// invalid input
|
|
if (base < 2 || base > 32)
|
|
return buffer;
|
|
|
|
// consider absolute value of number
|
|
int n = abs(value);
|
|
|
|
int i = 0;
|
|
while (n)
|
|
{
|
|
int r = n % base;
|
|
|
|
if (r >= 10)
|
|
buffer[i++] = 65 + (r - 10);
|
|
else
|
|
buffer[i++] = 48 + r;
|
|
|
|
n = n / base;
|
|
}
|
|
|
|
// if number is 0
|
|
if (i == 0)
|
|
buffer[i++] = '0';
|
|
|
|
// If base is 10 and value is negative, the resulting string
|
|
// is preceded with a minus sign (-)
|
|
// With any other base, value is always considered unsigned
|
|
if (value < 0 && base == 10)
|
|
buffer[i++] = '-';
|
|
|
|
buffer[i] = '\0'; // null terminate string
|
|
|
|
// reverse the string and return it
|
|
return reverse(buffer, 0, i - 1);
|
|
}
|
|
|
|
int maxi(int a, int b) {
|
|
if (a >= b) {
|
|
return a;
|
|
}
|
|
return b;
|
|
}
|
|
|
|
int mini(int a, int b) {
|
|
if (a <= b) {
|
|
return a;
|
|
}
|
|
return b;
|
|
}
|