Last active
November 1, 2018 18:36
-
-
Save Intey/7a7e204c0633c01097c6bd64ff79b181 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> // scanf, printf | |
#include <math.h> // pow | |
int slen(char* s) { | |
int res = 0; | |
while(*s) { res++; s++; } | |
return res; | |
} | |
int fromBin(char* s) { | |
int result = 0; | |
int len = slen(s); | |
for (int i = 0; i < len; ++i) { | |
if (s[i] == '0') { } | |
else if (s[i]== '1') { | |
result += 1 * pow(2, len - i - 1); | |
} | |
else { | |
return -1; | |
} | |
} | |
return result; | |
} | |
int fromDec(char* s) { | |
return 0; | |
} | |
int fromOct(char* s) { | |
int result = 0; | |
int len = 0; | |
len = slen(s); | |
for (int i = 0; i < len; ++i) { | |
if (s[i] == '0') { } | |
else if (s[i] == '1') { | |
result += 1 * pow(8, len - i -1); | |
} | |
else if (s[i] == '2') { | |
result += 2 * pow(8, len - i - 1); | |
} | |
else if (s[i] == '3') { | |
result += 3 * pow(8, len - i - 1); | |
} | |
else if (s[i] == '4') { | |
result += 4 * pow(8, len - i - 1); | |
} | |
else if (s[i] == '5') { | |
result += 5 * pow(8, len - i - 1); | |
} | |
else if (s[i] == '6') { | |
result += 6 * pow(8, len - i - 1); | |
} | |
else if (s[i] == '7') { | |
result += 7 * pow(8, len - i - 1); | |
} | |
else { | |
return -1; | |
} | |
} | |
return result; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
// +1 к длинне, чтобы считать \0 завершение строки, иначе массивы станут одим | |
// целым | |
int b = 0; | |
char r[7]; | |
scanf("%d", &b); | |
scanf("%6s", r); | |
printf("%d %s\n", b, r); | |
int v; // число в десятичной | |
char* res; // результирующая строка | |
if (b == 2) { | |
v = fromBin(r); | |
if (v < 0) | |
{ | |
printf("number is wrong\n"); | |
return 0; | |
} | |
printf("%x \n", v); | |
} else if (b == 8) { | |
v = fromOct(r); | |
if (v < 0) | |
{ | |
printf("number is wrong\n"); | |
return 0; | |
} | |
printf("%x\n", v); | |
} | |
else if (b == 10 ) { | |
v = fromDec(r); | |
if (v < 0) | |
{ | |
printf("number is wrong\n"); | |
return 0; | |
} | |
printf("%x\n", v); | |
} | |
else { | |
res = "base is wrong"; | |
printf("%s \n", res); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment