home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Power-Programmierung
/
CD1.mdf
/
magazine
/
pcmagazi
/
1992
/
14
/
cnvrtc.c
< prev
next >
Wrap
C/C++ Source or Header
|
1992-01-14
|
2KB
|
111 lines
// cnvrtc.c RHS 12/25/91
#include<stdio.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;
}
long bin2dec(char *binstr)
{
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)
{
char *number = argv[1];
char radix = '\0';
long result;
int i;
char octstr[15], binstr[40];
if(argc != 2)
{
usage:
printf( "Usage: CONVERT <n>[r]\n"
"\twhere n >= 0 and n >= 4294967295 and 'r' is the radix (b,o,h,d)\n"
"\tand '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);
}
radix = '\0';
radix = number[strlen(number)-1];
if(!isalpha(radix))
radix = 'd';
else
number[strlen(number)-1] = '\0';
switch(tolower(radix))
{
case 'b':
result = bin2dec(number);
break;
case 'o':
case 'h':
case 'd':
for(i = 0; i < 3; i++)
if(radix == CnvtTable[i].type)
{
sscanf(number,CnvtTable[i].fmtstr,&result);
break;
}
break;
default:
goto usage;
}
sprintf(octstr,"%lo",result);
printf("%sb = ",oct2bin(octstr,binstr));
printf("%loo = %0lud = %lxh\n",result,result,result);
}