home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Power-Programmierung
/
CD1.mdf
/
magazine
/
pcmagazi
/
1992
/
14
/
cnvrtcpp.cpp
< prev
next >
Wrap
C/C++ Source or Header
|
1992-01-16
|
2KB
|
119 lines
// cnvtcpp.cpp RHS 12/25/91
#include<stdio.h>
#include<iostream.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
char *binarystrs[8] = { "000", "001", "010", "011",
"100", "101", "110", "111" };
char *oct2bin(char *octstr, char *binstr)
{
char *temp = binstr;
for( *binstr = ' '; *octstr; octstr++)
{
strcpy(binstr,binarystrs[(*octstr)-'0']);
binstr += 3;
}
for(binstr = temp; *binstr == '0'; binstr++);
strcpy(temp,binstr);
return temp;
}
unsigned long bin2dec(char *binstr)
{
unsigned long result = 0L;
for( ; *binstr; binstr++)
result = (result*2) + (*binstr-'0');
return result;
}
typedef struct _convert
{
char type;
char *fmtstr;
} Convert;
Convert CnvtTable[3] =
{
{ 'o',"%lo", },
{ 'd',"%lu", },
{ 'h',"%lx", }
};
void main(int argc, char **argv)
{
if(argc != 2)
{
usage:
cout << "Usage: CONVERT <n>[r]\n"
"\twhere n >= 0 and n >= 4294967295 and 'r' is the radix (b,o,h,d)\n"
"\texamples: 10b Ah 3d 4o (binary 10, A hex, 3 decimal, 4 binary\n"
"\t(numbers without a radix are assumed to be decimal)\n";
exit(0);
}
char *number = argv[1];
char radix = '\0';
radix = '\0';
radix = number[strlen(number)-1];
if(!isalpha(radix))
radix = 'd';
else
number[strlen(number)-1] = '\0';
unsigned long result;
switch(tolower(radix))
{
case 'b':
result = bin2dec(number);
break;
case 'o':
case 'h':
case 'd':
int i;
for(i = 0; i < 3; i++)
if(radix == CnvtTable[i].type)
{
sscanf(number,CnvtTable[i].fmtstr,&result);
break;
}
break;
default:
goto usage;
}
char octstr[15], binstr[40];
sprintf(octstr,"%lo",result);
char *equal_sep = " = ";
cout << oct2bin(octstr,binstr) << 'b' << equal_sep;
cout << oct << result << 'o' << equal_sep;
cout << dec << result << 'd' << equal_sep;
cout << hex << result << 'h';
cout << '\n';
}