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,UN KNOWN} BASE; // test for the base of the
user input
static char *TrimLeadingZer o(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(cha r *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(t mp[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(c har *s) {
char *tmp;
tmp=TrimLeading Zero(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(1 6,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(cha r *s) {
char *tmp=s;
if(strlen(s)==0 )
return false;
while(*tmp!='\0 ') {
if(!isOctChar(* tmp))
return false;
++tmp;
}
return true;
}
static int OctString2Int(c har *s) {
char *tmp;
tmp=TrimLeading Zero(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,ns tr);
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(inpu t[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",arg v[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,&arg v[1][1]); // strip the oct-base header '0'
if(isOctString( tmp)) {
integer=OctStri ng2Int(tmp);
printf("%u\t%#x \n",integer,int eger);
}
else MakeAFuss();
break;
case HEX:
strcpy(tmp,&arg v[1][2]); // strip the hex-base header '0x' or '0X'
if(isHexString( tmp)) {
integer=HexStri ng2Int(tmp);
printf("%u\t%#o ",integer,integ er);
}
else MakeAFuss();
break;
default:
MakeAFuss();
}
return 0;
}
////////////////////// code end ///////////////////////// 8 6713
Just a very quick glance of your code brings up 2 questions to me. See
below
<snip> static char *TrimLeadingZer o(char *s) {
why are you using static functions?
<snip>
if(argc!=2) { fprintf(stderr, "Usage:\n\t %s <number>\n",arg v[0]); return 1; }
you should not 'return 1' as this is not portable, you should instead
include <stderr.h> and use EXIT(EXIT_FAILU RE);
Allan
"Allan Bruce" <al*****@TAKEAW AYf2s.com> wrote in
news:bu******** **@news.freedom 2surf.net: Just a very quick glance of your code brings up 2 questions to me. See below
<snip>
static char *TrimLeadingZer o(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",arg v[0]); return 1; }
you should not 'return 1' as this is not portable, you should instead include <stderr.h> and use EXIT(EXIT_FAILU RE);
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 ->
--
"Allan Bruce" <al*****@TAKEAW AYf2s.com> wrote: Just a very quick glance of your code brings up 2 questions to me. See below
static char *TrimLeadingZer o(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",arg v[0]); return 1; }
you should not 'return 1' as this is not portable, you should instead include <stderr.h> and use EXIT(EXIT_FAILU RE);
ITYM <stdlib.h> and exit(EXIT_FAILU RE)? 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
> ITYM <stdlib.h> and exit(EXIT_FAILU RE)? 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
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,UN KNOWN} BASE; // test for the base of the user input
static char *TrimLeadingZer o(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(cha r *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.l earn.c-c++ http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
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,UN KNOWN} BASE; // test for the base of the user input
static char *TrimLeadingZer o(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(cha r *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(t mp[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(c har *s) {
char *tmp;
tmp=TrimLeading Zero(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(1 6,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(cha r *s) {
char *tmp=s;
if(strlen(s)==0 ) return false;
while(*tmp!='\0 ') { if(!isOctChar(* tmp)) return false; ++tmp; }
return true; }
static int OctString2Int(c har *s) {
char *tmp;
tmp=TrimLeading Zero(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,ns tr);
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(inpu t[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",arg v[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,&arg v[1][1]); // strip the oct-base header '0' if(isOctString( tmp)) { integer=OctStri ng2Int(tmp); printf("%u\t%#x \n",integer,int eger); } else MakeAFuss(); break; case HEX: strcpy(tmp,&arg v[1][2]); // strip the hex-base header '0x' or '0X' if(isHexString( tmp)) { integer=HexStri ng2Int(tmp); printf("%u\t%#o ",integer,integ er); } else MakeAFuss(); break; default: MakeAFuss(); }
return 0; } ////////////////////// code end /////////////////////////
<<Remove the del for email>>
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,UN KNOWN} BASE; // test for the base of the user input
static char *TrimLeadingZer o(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(cha r *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(t mp[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(c har *s) {
char *tmp;
tmp=TrimLeading Zero(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(1 6,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(cha r *s) {
char *tmp=s;
if(strlen(s)==0 ) return false;
while(*tmp!='\0 ') { if(!isOctChar(* tmp)) return false; ++tmp; }
return true; }
static int OctString2Int(c har *s) {
char *tmp;
tmp=TrimLeading Zero(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,ns tr);
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(inpu t[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",arg v[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,&arg v[1][1]); // strip the oct-base header '0' if(isOctString( tmp)) { integer=OctStri ng2Int(tmp); printf("%u\t%#x \n",integer,int eger); } else MakeAFuss(); break; case HEX: strcpy(tmp,&arg v[1][2]); // strip the hex-base header '0x' or '0X' if(isHexString( tmp)) { integer=HexStri ng2Int(tmp); printf("%u\t%#o ",integer,integ er); } else MakeAFuss(); break; default: MakeAFuss(); }
return 0; } ////////////////////// code end ///////////////////////// <<Remove the del for email>>
Wow, amazing, thanx Barry! ru****@sohu.com (sugaray) wrote in
news:ad******** *************** ***@posting.goo gle.com:
[please learn to snip] <<Remove the del for email>>
Wow, amazing, thanx Barry!
--
- Mark ->
-- This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 value="large"/>
<xs:enumeration value="xlarge"/>
</xs:restriction>
</xs:simpleType>
|
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
uses message queues to pass pointers to Events between threads. In my app
there are simple events that can be defined using an enum (for example an
event called NETWORK_TIMEOUT) and more complex events that contain data
(for example an event called...
|
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 have run into is that the emitted html at the end of the
process is slightly different and doesn't work.
Please don't be put off by all the source code. All the guts are in this
first base class, and it doesn't do much. The rest is trivial...
|
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 Binding
window of the DataBindings dialog. I then found this site
(http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vsintro7/html/vxurfDataBindingsDialogBox.asp)
which says:
The tree view displays these objects: the Page object; any...
|
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;
namespace ConsoleProject1
{
public class Base
| |
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 data types, so
I have to implement the RTTI by myself.
I need a simple and effective example to help me decide how to design.
Can someon help me?
|
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);
|
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 because I am not
always able to control/create all the different constructors the base
class has. My problem can be described in code as follows ...
/* This is the base class with a whole heap of
constructors/functionality*/
public class Animal
|
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: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
|
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;
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |