From 53d3e939065aa7b7f98a807209b387a82012a3fd Mon Sep 17 00:00:00 2001 From: Steven Schronk Date: Wed, 23 Dec 2009 17:39:48 -0600 Subject: [PATCH] Created custom resuable library of favorite functions. Will continue to update in future. --- srs_lib.c | 88 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ srs_lib.h | 7 +++++ 2 files changed, 95 insertions(+) create mode 100644 srs_lib.c create mode 100644 srs_lib.h diff --git a/srs_lib.c b/srs_lib.c new file mode 100644 index 0000000..14c7835 --- /dev/null +++ b/srs_lib.c @@ -0,0 +1,88 @@ +#include +#include + +#include "srs_lib.h" + +/* print contents of array */ +void print_array(char s[]) +{ + int i; + for(i = 0; i < strlen(s); i++) + printf("%c", s[i]); + printf("\n"); +} + +/* print contents of array */ +void print_sparse_array(char s[][MAXLEN]) +{ + int i, j; + for(i = 0; i < MAXLINES; i++) + { + int found = 0; + for(j = 0; j < MAXLEN; j++) + { + if(s[i][j] != '\0') { found++; } + } + if(found > 0) + { + printf("%d:\t", i); + for(j = 0; j < MAXLEN; j++) + printf("%c", s[i][j]); + printf("\n"); + } + } + printf("\n"); +} + +/* reverse contents of array in place */ +void reverse(char s[]) +{ + int c, i, j; + for(i = 0, j = strlen(s)-1; i < j; i++, j--) + { + c = s[i]; + s[i] = s[j]; + s[j] = c; + } +} + +/* convert integer to another base and store result in array of char */ +int itob(int n, char s[], int b) +{ + int sign, i = 0; + + //create string of digits used to represent chars + char base_chars[] = { "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" }; + + //check that base is neither too high nor too small + if(b < 2) + { + printf("Base must be between 2 and %d.\n", (int)strlen(base_chars)-1); + return -1; + } + + if(b > strlen(base_chars)-1) + { + printf("Base must be %d or less.\n", (int)strlen(base_chars)-1); + return -1; + } + + // remove sign from number + if(n < 0) { n = -n; sign = 1; } + + + // increment s array and store in that location the modulus of the number -vs- the base + // while number divided by base is larger than 0 + i = 0; + do { + s[i++] = base_chars[n % b]; + } while ((n /= b) > 0); + + // add sign from above + if(sign == '1') { s[++i] = '-'; } + s[i] = '\0'; + + reverse(s); + return 1; +} + diff --git a/srs_lib.h b/srs_lib.h new file mode 100644 index 0000000..b7f1d61 --- /dev/null +++ b/srs_lib.h @@ -0,0 +1,7 @@ +#define MAXLINES 1000 +#define MAXLEN 1000 + +void print_array(char s[]); +void print_sparse_array(char s[][MAXLEN]); +int itob(int n, char s[], int b); + -- 2.11.4.GIT