/*************************************************************************** * Copyright (C) 2004 by Derek Rabideau * * xsynackx@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include int checkargs(int argc, char *argFrom, char *argTo); int convert(char argFrom, char *argNumber, char argTo); int bintodec(char *argBin); void printBin(int number); int main(int argc, char *argv[]) { if (!checkargs(argc, argv[1], argv[3])) { printf("Error, wrong number of arguments.\n"); return 0; } if(!convert(argv[1][0], argv[2], argv[3][0])) return EXIT_FAILURE; return EXIT_SUCCESS; } int checkargs(int argc, char *argFrom, char *argTo) { if (argc != 4) return 0; if (argFrom[0] == '-') { argFrom[0] = argFrom[1]; argFrom[1] = '\0'; } if (argTo[0] == '-') { argTo[0] = argTo[1]; argTo[1] = '\0'; } return 1; } int convert(char argFrom, char *argNumber, char argTo) { int num; if (argFrom == 'd') num = strtol(argNumber, NULL, 10); else if (argFrom == 'x') num = strtol(argNumber, NULL, 16); else if (argFrom == 'o') num = strtol(argNumber, NULL, 8); else if (argFrom == 'a') num = argNumber[0]; else if (argFrom == 'b') num = bintodec(argNumber); else { printf("ERROR: Input form not implemented.\n"); return 0; } if (argTo == 'x') printf("%#lx\n", num); else if (argTo == 'o') printf("%#lo\n", num); else if (argTo == 'a') { if (num < 32 || num > 126) printf("%lc (The output is probably a nonprintable control character.)\n", num); else printf("%lc\n", num);} else if (argTo == 'd') printf("%ld\n", num); else if (argTo == 'b') printBin(num); else {printf("ERROR: Conversion method not implemented.\n"); return 0; } return 1; } int bintodec(char *argBin) { unsigned int super, place, length; unsigned long int dec; dec = 0; length = strlen(argBin) - 1; super = length; for (place = 0; place <= length; ++place) { if (argBin[place] != '0') dec += pow(2, super); --super; } return dec; } void printBin(int number) { double super; super = 0; while (pow(2,super) <= number) { ++super; } --super; while (super >= 0) { number -= pow(2, super); printf("1"); --super; while(pow(2,super) > number && super >= 0) { printf("0"); --super; } } printf("\n"); }