-
Notifications
You must be signed in to change notification settings - Fork 3
/
lib_numsys.c
176 lines (127 loc) · 3.06 KB
/
lib_numsys.c
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include "lib_numsys.h"
int toBinaryInt(int decimal) {
int binary=0,base=1,i=0,length=0;
while(decimal>0) {
binary = (decimal%2)*base;
base*=10;
decimal = decimal/2;
i++;
length=i;
}
int bin_final = 0;
while(binary > 0)
{
bin_final = bin_final*10 + binary%10;
binary = binary/10;
}
return bin_final;
}
int* toBinary(int decimal) {
static int *binary;
binary = (int*) malloc(1*sizeof(int));
int i=0,length,ln;
while(decimal>0) {
*(binary+i) = decimal%2;
decimal = decimal/2;
i++;
length=i;
if(i>1) binary = realloc(binary,i);
}
i=0;
ln = length;
length = length-1;
while(i<length) {
int temp = *(binary+i);
*(binary+i) = *(binary+length);
*(binary+length) = temp;
i++;
length--;
}
*(binary+ln) = -1;
return binary;
}
char* toHexadecimal(int decimal) {
static char *hex;
hex = (char*) malloc(1*sizeof(char));
int i=0,length,ln;
while(decimal>0) {
int temp = decimal%16;
if(temp<10) {
*(hex+i) = temp + 48;
i++;
length=i;
}
else {
*(hex+i) = temp + 55;
i++;
length=i;
}
decimal = decimal/16;
if(i>1) hex = realloc(hex,i);
}
i=0;
ln = length;
length = length-1;
while(i<length) {
int temp = *(hex+i);
*(hex+i) = *(hex+length);
*(hex+length) = temp;
i++;
length--;
}
*(hex+ln) = '\0';
return hex;
}
int* toOctal(int decimal) {
static int *octal;
octal = (int*) malloc(1*sizeof(int));
int i=0,length,ln;
while(decimal>0) {
*(octal+i) = decimal%8;
decimal = decimal/8;
i++;
length=i;
if(i>1) octal = realloc(octal,i);
}
i=0;
ln = length;
length = length-1;
while(i<length) {
int temp = *(octal+i);
*(octal+i) = *(octal+length);
*(octal+length) = temp;
i++;
length--;
}
*(octal+ln) = -1;
return octal;
}
int toDecimal(char* number, int radix) {
static int decimal=0;
int i=0,j=0,length=strlen(number),base=1;
if(radix==16) {
decimal = 0;
for(i=length-1;i>=0;i--) {
if(*(number+i)>='0' && *(number+i)<='9') {
decimal += (*(number+i) - 48)*base;
base*=radix;
}
else {
decimal += (*(number+i) - 55)*base;
base*=radix;
}
}
}
else {
decimal = 0;
for(i=length-1;i>=0;i--) {
decimal += (*(number+i) - 48)*base;
base*=radix;
}
}
return decimal;
}