473,394 Members | 1,641 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

A simple base-converter program

hi, i wrote a simple base-conveter utility for practice, it seems
works fine right now, hope any gurus out there can give me some
suggestions to, critics of, optimisations on this program or my
programming practice. the code are mainly written in C, but need to be
compiled using a C++ compiler because of the using of builtin Boolean
type. it has been tested under VC7 and GCC 3.3.1. thanx in advance.

/////////////////////// code start /////////////////////
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

typedef enum {DEC,OCT,HEX,UNKNOWN} BASE; // test for the base of the
user input

static char *TrimLeadingZero(char *s) {

char *tmp=s;
while(*tmp=='0') tmp++;
return tmp;
}

static bool isHexChar(char c) {

return ((c>='a' && c<='f')||(c>='A' && c<='F')); // whether a valid
hex char
}

static bool isHexString(char *s) {

char *tmp=s;
size_t l,i;

if((l=strlen(s))==0) // expect no empty strings
return false;

for(i=0;i<l;++i)
if(!isHexChar(tmp[i]) && !isdigit(tmp[i])) // neither a valid hex
char nor a digit
return false;

return true;
}

static int Hex2Dec(char hex) {

if(isupper(hex))
return hex-'7'; // upper hex chars to integers
else if(islower(hex))
return hex-'W'; // lower hex chars to integers
else return hex-'0'; // digit chars to their corresponding integers
}

static int HexString2Int(char *s) {

char *tmp;

tmp=TrimLeadingZero(s);

int i,t;
int n=0;
size_t l=strlen(tmp);

for(i=l-1;i>=0;--i) {
t=Hex2Dec(*tmp);
if(t==0) {
tmp++;
continue; // jump out if is 0
}
n+=t*(int)pow(16,i);
++tmp;
}

return n;
}

static bool isOctChar(char c) {

return (c>='0' && c<='7'); // whether a valid octal char
}

static int Oct2Dec(char c) {

return c-'0'; // octal to it's corresponding decimal
integer
}

static bool isOctString(char *s) {

char *tmp=s;

if(strlen(s)==0)
return false;

while(*tmp!='\0') {
if(!isOctChar(*tmp))
return false;
++tmp;
}

return true;
}

static int OctString2Int(char *s) {

char *tmp;

tmp=TrimLeadingZero(s);

size_t l=strlen(tmp);
int i,t;
int n=0;

for(i=l-1;i>=0;--i) {
t=Oct2Dec(*tmp);
if(t==0) {
++tmp;
continue;
}
n+=t*(int)pow(8,i);
tmp++;
}
return n;
}

static BASE Base(char *nstr) {

char input[64];
strcpy(input,nstr);

if(input[0]=='0') // case for hex or octal
if(input[1]=='x' || input[1]=='X') // hex
return HEX;
else return OCT; // octal
else if(isdigit(input[0]) && input[0]!='0') // decimal
return DEC;
else return UNKNOWN; // unknown base
}

static void MakeAFuss(void) {

fprintf(stderr,"Hey pal, what the hell's that ?\n");
}

int main(int argc,char **argv)
{
BASE base;
char tmp[64]={0};
int integer;

if(argc!=2) {
fprintf(stderr,"Usage:\n\t%s <number>\n",argv[0]);
return 1;
}

base=Base((char *)argv[1]);

switch(base) {
case DEC:
printf("%#x\t%#o\n",atol(argv[1]),atol(argv[1]));
break;
case OCT:
strcpy(tmp,&argv[1][1]); // strip the oct-base header '0'
if(isOctString(tmp)) {
integer=OctString2Int(tmp);
printf("%u\t%#x\n",integer,integer);
}
else MakeAFuss();
break;
case HEX:
strcpy(tmp,&argv[1][2]); // strip the hex-base header '0x' or '0X'
if(isHexString(tmp)) {
integer=HexString2Int(tmp);
printf("%u\t%#o",integer,integer);
}
else MakeAFuss();
break;
default:
MakeAFuss();
}

return 0;
}
////////////////////// code end /////////////////////////
Nov 14 '05 #1
8 6695
Just a very quick glance of your code brings up 2 questions to me. See
below

<snip>

static char *TrimLeadingZero(char *s) {
why are you using static functions?

<snip>
if(argc!=2) {
fprintf(stderr,"Usage:\n\t%s <number>\n",argv[0]);
return 1;
}


you should not 'return 1' as this is not portable, you should instead
include <stderr.h> and use EXIT(EXIT_FAILURE);
Allan
Nov 14 '05 #2
"Allan Bruce" <al*****@TAKEAWAYf2s.com> wrote in
news:bu**********@news.freedom2surf.net:
Just a very quick glance of your code brings up 2 questions to me. See
below

<snip>

static char *TrimLeadingZero(char *s) {
why are you using static functions?


Why wouldn't you? Always maintain the tightest scope possible. For this
program the OP does not need to export any function to any other module.
Thus, all functions, except main, should be static. Export *only* what is
required by other modules.
<snip>
if(argc!=2) {
fprintf(stderr,"Usage:\n\t%s <number>\n",argv[0]);
return 1;
}


you should not 'return 1' as this is not portable, you should instead
include <stderr.h> and use EXIT(EXIT_FAILURE);


You stdlib.h where EXIT_FAILURE is defined (there is no stderr.h in ISO
C).

http://www.acm.uiuc.edu/webmonkeys/b...uide/2.13.html

--
- Mark ->
--
Nov 14 '05 #3
"Allan Bruce" <al*****@TAKEAWAYf2s.com> wrote:
Just a very quick glance of your code brings up 2 questions to me. See
below
static char *TrimLeadingZero(char *s) {


why are you using static functions?


Because it's wiser? I never bother to do this myself, but I'd prefer it
if internal linkage were the default.
if(argc!=2) {
fprintf(stderr,"Usage:\n\t%s <number>\n",argv[0]);
return 1;
}


you should not 'return 1' as this is not portable, you should instead
include <stderr.h> and use EXIT(EXIT_FAILURE);


ITYM <stdlib.h> and exit(EXIT_FAILURE)? There's no such thing as
<stderr.h> or EXIT(), but EXIT_FAILURE and exit() are in <stdlib.h>.
BTW, you can return EXIT_FAILURE from main() just as well.

Richard
Nov 14 '05 #4
> ITYM <stdlib.h> and exit(EXIT_FAILURE)? There's no such thing as
<stderr.h> or EXIT(), but EXIT_FAILURE and exit() are in <stdlib.h>.
BTW, you can return EXIT_FAILURE from main() just as well.

Richard


Oh dear I am having an off day today!
Allan
Nov 14 '05 #5
On 21 Jan 2004 04:42:49 -0800, ru****@sohu.com (sugaray) wrote in
comp.lang.c:

[snip]
/////////////////////// code start /////////////////////
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

typedef enum {DEC,OCT,HEX,UNKNOWN} BASE; // test for the base of the
user input

static char *TrimLeadingZero(char *s) {

char *tmp=s;
while(*tmp=='0') tmp++;
return tmp;
}

static bool isHexChar(char c) {

return ((c>='a' && c<='f')||(c>='A' && c<='F')); // whether a valid
hex char
}
Apparently you are posting C++ code to comp.lang.c. Don't do that.
There is no such thing as "bool" in C unless you have a conforming C99
implementation, which I have been informed Visual C++ 7 is NOT, and
even then it requires including <stdbool.h>, which you have not.

Also this function can be performed much better by combining two
standard functions from <ctype.h>:

return isxdigit(c) && !isdigit(c);
static bool isHexString(char *s) {


Don't post C++ code to comp.lang.c.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #6
On 21 Jan 2004 04:42:49 -0800, ru****@sohu.com (sugaray) wrote:
hi, i wrote a simple base-conveter utility for practice, it seems
works fine right now, hope any gurus out there can give me some
suggestions to, critics of, optimisations on this program or my
programming practice. the code are mainly written in C, but need to be
compiled using a C++ compiler because of the using of builtin Boolean
type. it has been tested under VC7 and GCC 3.3.1. thanx in advance.

/////////////////////// code start /////////////////////
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

typedef enum {DEC,OCT,HEX,UNKNOWN} BASE; // test for the base of the
user input

static char *TrimLeadingZero(char *s) {

char *tmp=s;
while(*tmp=='0') tmp++;
return tmp;
}

static bool isHexChar(char c) {
Is there some reason you don't like the standard function isxdigit()?

return ((c>='a' && c<='f')||(c>='A' && c<='F')); // whether a valid
hex char
There is no requirement in the C standards for a through f and/or A
through F to be sequential. It would be legal for the character set
to have the character + between a and b.
}

static bool isHexString(char *s) {

char *tmp=s;
size_t l,i;

if((l=strlen(s))==0) // expect no empty strings
return false;

for(i=0;i<l;++i)
if(!isHexChar(tmp[i]) && !isdigit(tmp[i])) // neither a valid hex
char nor a digit
return false;

return true;
}

static int Hex2Dec(char hex) {

if(isupper(hex))
return hex-'7'; // upper hex chars to integers
This only works for ASCII characters. It doesn't even come close for
EBCDIC.
else if(islower(hex))
return hex-'W'; // lower hex chars to integers
else return hex-'0'; // digit chars to their corresponding integers
}

static int HexString2Int(char *s) {

char *tmp;

tmp=TrimLeadingZero(s);

int i,t;
int n=0;
size_t l=strlen(tmp);

for(i=l-1;i>=0;--i) {
If you put the tmp++ in the third clause of the for statement, you can
get rid of both increment statements below.
t=Hex2Dec(*tmp);
if(t==0) {
tmp++;
continue; // jump out if is 0
}
n+=t*(int)pow(16,i);
++tmp;
}
You could get rid of the call to pow completely (it has to be
expensive in terms of time) by evaluating the hex string from left to
right. Something like
for (s = TrinLeadingZero(s); *s ; s++)
n = n*16 + Hex2Dec(*s);
which also allow you to get rid of i, t, tmp, and l.

return n;
}

static bool isOctChar(char c) {

return (c>='0' && c<='7'); // whether a valid octal char
The 10 decimal characters are guaranteed to be sequential so this will
work.
}

static int Oct2Dec(char c) {

return c-'0'; // octal to it's corresponding decimal
integer
}

static bool isOctString(char *s) {

char *tmp=s;

if(strlen(s)==0)
return false;

while(*tmp!='\0') {
if(!isOctChar(*tmp))
return false;
++tmp;
}

return true;
}

static int OctString2Int(char *s) {

char *tmp;

tmp=TrimLeadingZero(s);

size_t l=strlen(tmp);
int i,t;
int n=0;

for(i=l-1;i>=0;--i) {
t=Oct2Dec(*tmp);
if(t==0) {
++tmp;
continue;
}
n+=t*(int)pow(8,i);
tmp++;
}
return n;
}

static BASE Base(char *nstr) {

char input[64];
strcpy(input,nstr);

if(input[0]=='0') // case for hex or octal
if(input[1]=='x' || input[1]=='X') // hex
return HEX;
else return OCT; // octal
else if(isdigit(input[0]) && input[0]!='0') // decimal
The second half of the if must always be true because this is the else
to the very first if above.
return DEC;
else return UNKNOWN; // unknown base
}

static void MakeAFuss(void) {

fprintf(stderr,"Hey pal, what the hell's that ?\n");
}

int main(int argc,char **argv)
{
BASE base;
char tmp[64]={0};
int integer;

if(argc!=2) {
fprintf(stderr,"Usage:\n\t%s <number>\n",argv[0]);
return 1;
}

base=Base((char *)argv[1]);
argv is a char**. Therefore, argv[1] must be of type char. Why the
cast?

switch(base) {
case DEC:
printf("%#x\t%#o\n",atol(argv[1]),atol(argv[1]));
atol returns a long. %x and %o both require the corresponding
argument to be int. You need some casts.
break;
case OCT:
strcpy(tmp,&argv[1][1]); // strip the oct-base header '0'
if(isOctString(tmp)) {
integer=OctString2Int(tmp);
printf("%u\t%#x\n",integer,integer);
}
else MakeAFuss();
break;
case HEX:
strcpy(tmp,&argv[1][2]); // strip the hex-base header '0x' or '0X'
if(isHexString(tmp)) {
integer=HexString2Int(tmp);
printf("%u\t%#o",integer,integer);
}
else MakeAFuss();
break;
default:
MakeAFuss();
}

return 0;
}
////////////////////// code end /////////////////////////


<<Remove the del for email>>
Nov 14 '05 #7
Barry Schwarz <sc******@deloz.net> wrote in message news:<bu**********@216.39.134.8>...
On 21 Jan 2004 04:42:49 -0800, ru****@sohu.com (sugaray) wrote:
hi, i wrote a simple base-conveter utility for practice, it seems
works fine right now, hope any gurus out there can give me some
suggestions to, critics of, optimisations on this program or my
programming practice. the code are mainly written in C, but need to be
compiled using a C++ compiler because of the using of builtin Boolean
type. it has been tested under VC7 and GCC 3.3.1. thanx in advance.

/////////////////////// code start /////////////////////
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

typedef enum {DEC,OCT,HEX,UNKNOWN} BASE; // test for the base of the
user input

static char *TrimLeadingZero(char *s) {

char *tmp=s;
while(*tmp=='0') tmp++;
return tmp;
}

static bool isHexChar(char c) {


Is there some reason you don't like the standard function isxdigit()?

return ((c>='a' && c<='f')||(c>='A' && c<='F')); // whether a valid
hex char


There is no requirement in the C standards for a through f and/or A
through F to be sequential. It would be legal for the character set
to have the character + between a and b.
}

static bool isHexString(char *s) {

char *tmp=s;
size_t l,i;

if((l=strlen(s))==0) // expect no empty strings
return false;

for(i=0;i<l;++i)
if(!isHexChar(tmp[i]) && !isdigit(tmp[i])) // neither a valid hex
char nor a digit
return false;

return true;
}

static int Hex2Dec(char hex) {

if(isupper(hex))
return hex-'7'; // upper hex chars to integers


This only works for ASCII characters. It doesn't even come close for
EBCDIC.
else if(islower(hex))
return hex-'W'; // lower hex chars to integers
else return hex-'0'; // digit chars to their corresponding integers
}

static int HexString2Int(char *s) {

char *tmp;

tmp=TrimLeadingZero(s);

int i,t;
int n=0;
size_t l=strlen(tmp);

for(i=l-1;i>=0;--i) {


If you put the tmp++ in the third clause of the for statement, you can
get rid of both increment statements below.
t=Hex2Dec(*tmp);
if(t==0) {
tmp++;
continue; // jump out if is 0
}
n+=t*(int)pow(16,i);
++tmp;
}


You could get rid of the call to pow completely (it has to be
expensive in terms of time) by evaluating the hex string from left to
right. Something like
for (s = TrinLeadingZero(s); *s ; s++)
n = n*16 + Hex2Dec(*s);
which also allow you to get rid of i, t, tmp, and l.

return n;
}

static bool isOctChar(char c) {

return (c>='0' && c<='7'); // whether a valid octal char


The 10 decimal characters are guaranteed to be sequential so this will
work.
}

static int Oct2Dec(char c) {

return c-'0'; // octal to it's corresponding decimal
integer
}

static bool isOctString(char *s) {

char *tmp=s;

if(strlen(s)==0)
return false;

while(*tmp!='\0') {
if(!isOctChar(*tmp))
return false;
++tmp;
}

return true;
}

static int OctString2Int(char *s) {

char *tmp;

tmp=TrimLeadingZero(s);

size_t l=strlen(tmp);
int i,t;
int n=0;

for(i=l-1;i>=0;--i) {
t=Oct2Dec(*tmp);
if(t==0) {
++tmp;
continue;
}
n+=t*(int)pow(8,i);
tmp++;
}

return n;
}

static BASE Base(char *nstr) {

char input[64];
strcpy(input,nstr);

if(input[0]=='0') // case for hex or octal
if(input[1]=='x' || input[1]=='X') // hex
return HEX;
else return OCT; // octal
else if(isdigit(input[0]) && input[0]!='0') // decimal


The second half of the if must always be true because this is the else
to the very first if above.
return DEC;
else return UNKNOWN; // unknown base
}

static void MakeAFuss(void) {

fprintf(stderr,"Hey pal, what the hell's that ?\n");
}

int main(int argc,char **argv)
{
BASE base;
char tmp[64]={0};
int integer;

if(argc!=2) {
fprintf(stderr,"Usage:\n\t%s <number>\n",argv[0]);
return 1;
}

base=Base((char *)argv[1]);


argv is a char**. Therefore, argv[1] must be of type char. Why the
cast?

switch(base) {
case DEC:
printf("%#x\t%#o\n",atol(argv[1]),atol(argv[1]));


atol returns a long. %x and %o both require the corresponding
argument to be int. You need some casts.
break;
case OCT:
strcpy(tmp,&argv[1][1]); // strip the oct-base header '0'
if(isOctString(tmp)) {
integer=OctString2Int(tmp);
printf("%u\t%#x\n",integer,integer);
}
else MakeAFuss();
break;
case HEX:
strcpy(tmp,&argv[1][2]); // strip the hex-base header '0x' or '0X'
if(isHexString(tmp)) {
integer=HexString2Int(tmp);
printf("%u\t%#o",integer,integer);
}
else MakeAFuss();
break;
default:
MakeAFuss();
}

return 0;
}
////////////////////// code end /////////////////////////


<<Remove the del for email>>


Wow, amazing, thanx Barry!
Nov 14 '05 #8
ru****@sohu.com (sugaray) wrote in
news:ad**************************@posting.google.c om:

[please learn to snip]
<<Remove the del for email>>


Wow, amazing, thanx Barry!


--
- Mark ->
--
Nov 14 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: scorpion | last post by:
I have a simple type like this: <xs:simpleType name="SizeType"> <xs:restriction base="xs:token"> <xs:enumeration value="small"/> <xs:enumeration value="medium"/> <xs:enumeration...
8
by: Mark | last post by:
Hi, I'm looking for some ideas on how to build a very simple Event processing framework in my C++ app. Here is a quick background ... I'm building a multithreaded app in C++ (on Linux) that...
0
by: 42 | last post by:
I implemented a simple class inherited from Page to create a page template. It simply wraps some trivial html around the inherited page, and puts the inherited page into a form. The problem I...
0
by: Ian | last post by:
I have sub-classed the Page class in order to provide some base properties and methods that every page on my site will need access to. I would like to have these things show up in the Simple...
1
by: relient | last post by:
Hi, I just started the chapter on "Inheritance" and I'm a bit confused so I have three questions: first, here's the code: using System; using System.Collections.Generic; using System.Text; ...
5
by: dotNeter | last post by:
I'm studying the RTTI, and my current work is concern for how to get the self-defined type at runtime, that's exactly what the RTTI does. I mean, in my application, I built several self-defined...
10
by: Ivan Vecerina | last post by:
Here's a relatively simple code snippet: #include <memory> class Base { public: Base(); virtual ~Base(); virtual void f(int a, char const* name);
26
by: nyathancha | last post by:
Hi, How Do I create an instance of a derived class from an instance of a base class, essentially wrapping up an existing base class with some additional functionality. The reason I need this is...
5
by: Michael | last post by:
Hi All, I have three very simple files as below. When I try and compile these with g++ -ansi -Wall -pedantic -o crap Base.h Other.h I get an error: Base.h:7: internal compiler error:...
26
by: optimistx | last post by:
A variable in global scope var a1 = 'contents of global variable a1'; can be references (with some limitations) as window; // or window.a1; // or even window;
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.