473,776 Members | 1,505 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

K&R 2 exercise 2-3

Hi~ i've studied C for a few months myself,

and i'd appreciate it if anyone could improve my coding or correct it.

the following is my solution to the K&R exercise 2-3

"Write the function htoi(s), which converts a string of hexademical digits
(including an optional 0x or 0X) into its equivalent integer value.
The allowable digits are 0 through 9, a through f, and A throught F."
//*************** *************** *************** *************** **************

#include <stdio.h>

int isxdigit2(int c)
{
if ( (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9') )
return 1;
else
return 0;
}

int tolower2(int c)
{
if (c >= 'A' && c <= 'Z')
return c+32;
else
return c;
}

int power2(int base, int num)
{
int sum;
for (sum = 1; num >0 ; num --)
sum *= base;
return sum;
}

int char_to_num(int c)
{
if (c >= '0' && c <= '9')
{
return c - 48;
}
else
{
return 10 + (tolower2(c) - 'a');
}
}

int htoi(char *c)
{
int i, k, prefix = 0;
size_t sum = 0;

if (c[0] == '0' && tolower2(c[1]) == 'x')
prefix = 1;

for (i = (prefix == 1)? 2:0 ; c[i] ;i++ )
{
if (!isxdigit2(c[i]) )
{
printf("Wrong hexa number\n");
return 0;
}
c[i] = char_to_num(c[i]);
}

for (k = (prefix == 1)? 2 : 0 ; k <= i-1 ; ++k )
{
sum += c[k] * power2(16, i-1-k);
}

return sum;
}

int main()
{
char c[] = "0xAB";
printf("%u", htoi(c));

return 0;
}

//*************** *************** *************** *************** ******

when i change char c[] to char *c in main(),
it shows error, why ??

Thanks..
Nov 14 '05
46 3707
"nrk" <ra*********@de vnull.verizon.n et> wrote:
Irrwahn Grausewitz wrote:
he*********@kor net.net (Herrcho) wrote:
static const char *uppercase = "ABCDEFGHIJKLMN OPQRSTUVWXYZ";
static const char *lowercase = "abcdefghijklmn opqrstuvwxyz";

Nitpick:
static const char const *...


Nitpick, ITYM:
static const char * const ...

Here, and in other places as well :-)


Correct, though I would use:
static const char uppercase[] = ...
static const char lowercase[] = ...

There are two advantages:
1. Saving 2*sizeof(char*) bytes, and
2. Being able to apply sizeof to 'uppercase' and 'lowercase'.

I am not aware of any disadvantages ;-)

Peter
Nov 14 '05 #21
nrk <ra*********@de vnull.verizon.n et> wrote:
Irrwahn Grausewitz wrote:
he*********@kor net.net (Herrcho) wrote:
<snip>
static const char *lowercase = "abcdefghijklmn opqrstuvwxyz";

Nitpick:
static const char const *...


Nitpick, ITYM:
static const char * const ...

Here, and in other places as well :-)


Umm, yes, don't know what I was thinking.
Thanks for correction. :-)

Regards
--
Irrwahn Grausewitz (ir*******@free net.de)
welcome to clc : http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
acllc-c++ faq : http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #22
Martin O'Brien wrote:
/* hex2int.c: Convert hexadecimal number in any locale */
/* Source: THE STANDARD C LIBRARY by P J Plauger, p34 */
/* NOTE: This code does not check for overflow. That requires */
/* additional complexity. */

#include <ctype.h>
#include <string.h>

int hex2int(const char *s)
{
int value;
static const char xd[] =
{"0123456789abc defABCDEF"};

static const char xv[] =
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15,
10, 11, 12, 13, 14, 15};

for (value = 0; isxdigit(*s); ++s)
value = (value << 4) + xv[strchr(xd, *s) - xd];

return value;


I believe htoi() should return an unsigned int (perhaps unsigned long).
AFAIK, you cannot portably represent signed values in hex. In any case,
Plauger's code exhibits undefined behavior, so this is definitely not
the implementation you want to use.

/david

--
Andre, a simple peasant, had only one thing on his mind as he crept
along the East wall: 'Andre, creep... Andre, creep... Andre, creep.'
-- unknown
Nov 14 '05 #23
David wrote:
I believe htoi() should return an
unsigned int (perhaps unsigned long). AFAIK,
you cannot portably represent signed values in hex.
In any case, Plauger's code exhibits undefined
behavior, so this is definitely not the
implementation you want to use.


The mistake is mine. I wrapped Plauger's code in a function definition
and wrongly put the return type as int.

Plauger says this:

---
To convert a hexadecimal number in any locale, write:

#include <ctype.h>
#include <string.h>
....
static const char xd[] =
{"0123456789abc defABCDEF"};

static const char xv[] =
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15,
10, 11, 12, 13, 14, 15};

for (value = 0; isxdigit(*s); ++s)
value = (value << 4) + xv[strchr(xd, *s) - xd];

Note that this code does not check for overflow. That requires
additional complexity.
---

Martin
http://martinobrien.co.uk/
Nov 14 '05 #24
Martin O'Brien wrote:

David wrote:
I believe htoi() should return an
unsigned int (perhaps unsigned long). AFAIK,
you cannot portably represent signed values in hex.
In any case, Plauger's code exhibits undefined
behavior, so this is definitely not the
implementation you want to use.


The mistake is mine. I wrapped Plauger's code in a function
definition and wrongly put the return type as int.

Plauger says this:

---
To convert a hexadecimal number in any locale, write:

#include <ctype.h>
#include <string.h>
...
static const char xd[] =
{"0123456789abc defABCDEF"};

static const char xv[] =
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15,
10, 11, 12, 13, 14, 15};

for (value = 0; isxdigit(*s); ++s)
value = (value << 4) + xv[strchr(xd, *s) - xd];

Note that this code does not check for overflow. That requires
additional complexity.


It still exhibits undefined behaviour. You need to define value.
Also s, although we can make some assumptions about that.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #25
"CBFalconer " wrote:
It still exhibits undefined behaviour. You need to define value.
Also s, although we can make some assumptions about that.


I'm puzzled. How can it exhibit anything if it doesn't compile?

Martin

Nov 14 '05 #26
On 19 Feb 2004 00:33:08 -0800, ma************@ which.net (Martin
O'Brien) wrote:
David wrote:
I believe htoi() should return an
unsigned int (perhaps unsigned long). AFAIK,
you cannot portably represent signed values in hex.
In any case, Plauger's code exhibits undefined
behavior, so this is definitely not the
implementation you want to use.


The mistake is mine. I wrapped Plauger's code in a function definition
and wrongly put the return type as int.

Plauger says this:

---
To convert a hexadecimal number in any locale, write:

#include <ctype.h>
#include <string.h>
...
static const char xd[] =
{"0123456789abc defABCDEF"};

static const char xv[] =
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15,
10, 11, 12, 13, 14, 15};

for (value = 0; isxdigit(*s); ++s)
value = (value << 4) + xv[strchr(xd, *s) - xd];

Note that this code does not check for overflow. That requires
additional complexity.
---

Martin
http://martinobrien.co.uk/


htoi1 "check for overflow" ? Is it right?
How checking for overflow?

#include <stdio.h>
int lower(int c)
{if(c>='A' && c<='Z') return c+'a'-'A';
else return c;
}

int isdigit(int c)
{if(c>='0' && c<='9') return 1; else return 0;}

int ispace(int c)
{ if(c==' ' || c=='\t' || c=='\n') return 1; else return 0;}
int htoi1(char s[])
{unsigned i=0, n=0, d, h;
char c;

while( (c=s[i])==' ' || c=='\t' || c=='\n' )
i++;
if( c=='0' && ( s[i+1]=='x' || s[i+1]=='X') )
{i+=2; c=s[i];}
while(1)
{d= ('0'<=c && c<='9' ) ? c - '0' :
( c>='A' && c<='F' ) ? c - 'A' + 10:
( c>='a' && c<='f' ) ? c - 'a' + 10: 16;
if(d==16)
break;
if( (h=16 * n) < n || (n=h+d)<h || n<d )
{n= ((int)n)>0 ? ((~0u)>>1) : ((~0u)>>1)+1; break;}
c=s[++i];
}
return (int) n;
}
int htoi(char s[])
{int i=0,n=0;
while(ispace(s[i])) i++;
if(s[i]=='0'&& lower(s[i+1])=='x') i+=2;
for( ; ;++i)
if( isdigit(s[i]) ) n=16*n + (s[i]-'0');
else if((lower(s[i])>='a' && lower(s[i])<='f'))
n=16*n+lower(s[i])-'a'+ 10;
else break;
return n;
}

main()
{char b[30];
int c, ch, j;
do{printf("\nLi sta di numeri esadecinmali(1 termina)>");
do{scanf("%s", &b);
c=htoi1(b);
printf("\nParte nza=%s\n",b);
printf("Arrivo =%d\n", c);
c=htoi(b);
printf("\nParte nza=%s\n",b);
printf("Arrivo =%d\n", c);
if((ch=fgetc(st din) )=='\n') break;
else ungetc(ch,stdin );
} while(ch!=EOF );
}while(c!=1);
return 0;
}

Nov 14 '05 #27
Hello RoRsOaMrPiEo.

Your code is very busy. Why are you writing functions lower(), isdigit() and
isspace() when the Standard Library has them? (in the C Library lower() is
called tolower()).

And this thread should have convinced you that although you can assume the
characters '0' to '9' have consecutive values, you can not make that
assumption about upper and lower case letters. Which is why Plauger uses a
table of values xv, to define the values of the characters in xd.

Also, Chuck has already said that my function wrapper around Plauger's
suggestion was faulty because it returned int, which was an oversight on my
part, and your function now does the same, and even casts the results of its
calculations (in an unsigned int) to int before returning it.

I think what Plauger means about additional complexity for overflow is to
flag a warning if overflow is indicated and stop the conversion. It's what
I'd do anyway.

--
Martin
http://martinobrien.co.uk/
"RoRsOaMrPi Eo" wrote:
htoi1 "check for overflow" ? Is it right?
How checking for overflow?

#include <stdio.h> [...]
} while(ch!=EOF ); }while(c!=1);
return 0;
}


Nov 14 '05 #28
"Martin" <martin.o_brien @[no-spam]which.net> writes:
"CBFalconer " wrote:
It still exhibits undefined behaviour. You need to define value.
Also s, although we can make some assumptions about that.


I'm puzzled. How can it exhibit anything if it doesn't compile?


"Undefined behavior" means that the standard poses no requirements on
how a conforming implementation behaves. If a compiler is part of the
implementation, not compiling the code at all is therefore just as
allowed as generating executable code.

(FWIW, there are cases of undefined behavior which only occurs at
run-time for some input data. An obvious example is any program which
calls the `gets' function. In such cases, the compiler must compile the
program.)
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
Nov 14 '05 #29
RoRsOaMrPiEo wrote:
.... snip ...
#include <stdio.h>

int lower(int c)
{if(c>='A' && c<='Z') return c+'a'-'A';
else return c;
}


Already non-portable code, with foul formatting. I see at least
four blanks you could have saved.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #30

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

Similar topics

6
3806
by: leonard greeff | last post by:
I want to know the correct way to answer exercise 1-11 of K&R. The only bug that I can find is that nw counts one to many words. (if there are 8 words, nw will be 9) Am I correct aor is there more to it leonard
12
2178
by: Chris Readle | last post by:
Ok, I've just recently finished a beginning C class and now I'm working through K&R2 (alongside the C99 standard) to *really* learn C. So anyway, I'm working on an exercise in chapter one which give me strange behavior. Here is the code I've written: /****************************************************************************** * K&R2 Exercise 1-9 * Write a program to copy its input to its output, replacing strings of blanks * with a...
12
2337
by: Merrill & Michele | last post by:
It's very difficult to do an exercise with elementary tools. It took me about fifteen minutes to get exercise 1-7: #include <stdio.h> int main(int orange, char **apple) { int c; c=-5; while(c != EOF ) {
8
3087
by: Mike S | last post by:
Hi all, I noticed a very slight logic error in the solution to K&R Exercise 1-22 on the the CLC-Wiki, located at http://www.clc-wiki.net/wiki/KR2_Exercise_1-22 The exercise reads as follows: "Write a program to 'fold' long input lines into two or more shorter
16
2281
by: Josh Zenker | last post by:
This is my attempt at exercise 1-10 in K&R2. The code looks sloppy to me. Is there a more elegant way to do this? #include <stdio.h> /* copies input to output, printing */ /* series of blanks as a single one */ int main() { int c;
19
2407
by: arnuld | last post by:
this programme runs without any error but it does not do what i want it to do: ------------- PROGRAMME -------------- /* K&R2, section 1.6 Arrays; Exercise 1-13. STATEMENT: Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical
5
2919
by: arnuld | last post by:
this is a programme that counts the "lengths" of each word and then prints that many of stars(*) on the output . it is a modified form of K&R2 exercise 1-13. the programme runs without any compile-error BUT it has a semantic BUG: what i WANT: I want it to produce a "horizontal histogram" which tells how many characters were in the 1st word, how many characters were in the second word by writing equal number of stars, *, at the...
9
3044
by: JFS | last post by:
I know most of you have probably read "The C Programming Language" (K&R) at some point. Well here is something that is driving me crazy. The exercises are impossible (most of them) for me to do. I am not even done with the first chapter and I am already ripping out my hair trying to get the exercises completed. It is driving me crazy and making me very very angry. Here is an example of what I am talking about: Chapter 1.6 Arrays...
88
3796
by: santosh | last post by:
Hello all, In K&R2 one exercise asks the reader to compute and print the limits for the basic integer types. This is trivial for unsigned types. But is it possible for signed types without invoking undefined behaviour triggered by overflow? Remember that the constants in limits.h cannot be used.
0
9628
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, 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...
0
9464
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,...
0
10120
jinu1996
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...
0
9923
tracyyun
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...
0
6722
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();...
0
5367
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4031
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
2
3622
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2860
bsmnconsultancy
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...

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.