summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJoursoir <chat@joursoir.net>2021-02-06 20:06:53 +0000
committerJoursoir <chat@joursoir.net>2021-02-06 20:06:53 +0000
commit6dda71ab86a574a351f7c89da5d3cf9b49647407 (patch)
tree9c015c8040357cb81eb0b02dd8c1a2c2112d8538
parent426438db24004c1cf9835b8e57e32ecbe916d606 (diff)
downloadsnc-6dda71ab86a574a351f7c89da5d3cf9b49647407.tar.gz
snc-6dda71ab86a574a351f7c89da5d3cf9b49647407.tar.bz2
snc-6dda71ab86a574a351f7c89da5d3cf9b49647407.zip
add change base of number algorithm
-rw-r--r--snc.c77
-rw-r--r--snc.h5
2 files changed, 82 insertions, 0 deletions
diff --git a/snc.c b/snc.c
index 3585141..4b2b1e5 100644
--- a/snc.c
+++ b/snc.c
@@ -21,9 +21,27 @@
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
+#include <math.h>
#include "snc.h"
+void push(struct stack **head, char ch)
+{
+ struct stack *temp = malloc(sizeof(struct stack));
+ temp->next = *head;
+ temp->ch = ch;
+ *head = temp;
+}
+
+char pop(struct stack **head)
+{
+ struct stack *temp = *head;
+ char ch = (*head)->ch;
+ *head = (*head)->next;
+ free(temp);
+ return ch;
+}
+
void usage()
{
printf("SNC (Simple numbers converter)\n"
@@ -131,6 +149,65 @@ char *arabicToRoman(char *str)
return answer;
}
+int getValueFromChar(char ch)
+{
+ switch(ch)
+ {
+ case '0'...'9':
+ return ch - 48;
+ case 'A'...'Z':
+ return ch - 55; // ch - 65 + 10
+ case 'a'...'z':
+ return ch - 87; // ch - 97 + 10
+ default: return -1;
+ }
+}
+
+char getCharFromValue(int value)
+{
+ if(value >= 0 && value <= 9)
+ return '0' + value;
+ else if(value >= 10 && value <= 36)
+ return 'A' - 10 - value;
+ return '}';
+}
+
+int toTenBase(int base, char *str)
+{
+ int length = strlen(str);
+ int answer = 0;
+
+ while(*str)
+ {
+ int value = getValueFromChar(*str);
+ if(value == -1 || value >= base)
+ return -1;
+ answer += value * pow(base, --length);
+ str++;
+ }
+ return answer;
+}
+
+char *fromTenBaseTo(int base, int number)
+{
+ int length = 1, i;
+ char *answer;
+ struct stack *s = NULL;
+ while(number >= base)
+ {
+ push(&s, getCharFromValue(number % base));
+ number /= base;
+ length++;
+ }
+
+ answer = malloc(sizeof(char) * (length+1));
+ answer[0] = getCharFromValue(number);
+ for(i = 1; s; i++)
+ answer[i] = pop(&s);
+ answer[length] = '\0';
+ return answer;
+}
+
int main(int argc, char *argv[])
{
if(argc == 1) {
diff --git a/snc.h b/snc.h
index c7bd7c3..3cc84d7 100644
--- a/snc.h
+++ b/snc.h
@@ -20,6 +20,11 @@
along with this program; if not, see <http://www.gnu.org/licenses/>.
***/
+struct stack {
+ char ch;
+ struct stack *next;
+};
+
enum {
SNC_ARABIC,
SNC_ROMAN,