473,776 Members | 1,557 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
On Fri, 20 Feb 2004 14:12:54 GMT, RoRsOaMrPiEo <n@esiste.ee> wrote:
On Fri, 20 Feb 2004 12:32:52 GMT, rl*@hoekstra-uitgeverij.nl (Richard
Bos) wrote:
> #include <limits.h>
> #include <stdlib.h>
>
> unsigned int htoi(char *txt)
> {
> unsigned long tmp=strtoul(txt , 0, 16);
> if (tmp>UINT_MAX) return UINT_MAX;
> return tmp;
> }

but here htoi(8eeeeeeeee eeeeeeeeeeeeee) ==-1

this seems htoi(8eeeeeeeee eeeeeeeeeeeeee) == INT_MAX


Imprimis, htoi(8eeeeeeeee eeeeeeeeee) is a syntax error.
Secundis, htoi("8eeeeeeee eeeeeeeeeeee") invokes undefined behaviour for
your implementation (and thus has a license to return anything,
including garbage, and even crash the machine), and returns UINT_MAX
(not INT_MAX) for my implementation, without being undefined.


so your is htou and not htoi

is there any pc where
(int) (unsigned) INT_MAX != INT_MAX (this would be true for K&R?)
or where
(int) (unsigned) INT_MIN != INT_MIN

or where if zE{INT_MIN...IN T_MAX}
then (int) (unsigned) z != z
Nov 14 '05 #41
Martin wrote:
"Richard Bos" wrote:
Why do work which the library will do for you?

#include <limits.h>
#include <stdlib.h>

unsigned int htoi(char *txt)
{
unsigned long tmp=strtoul(txt , 0, 16);
if (tmp>UINT_MAX) return UINT_MAX;
return tmp;
}

Shorter, sweeter, doesn't waste value space on
negative numbers which you don't parse anyway,
doesn't invoke undefined behaviour on overflow,
and is portable no matter what your character set it.
Feel free.


Isn't there a possibility that UINT_MAX == ULONG_MAX?


So? As before, this means input >= UINT_MAX returns UINT_MAX.

--
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 #42
"CBFalconer " wrote:
So? As before, this means input >= UINT_MAX returns UINT_MAX.


If UINT_MAX == ULONG_MAX then tmp>UINT_MAX can never be true and UINT_MAX
will never be returned by your function, even when overflow occurs.

Martin
http://martinobrien.co.uk/

Nov 14 '05 #43
Martin wrote:
"CBFalconer " wrote:
So? As before, this means input >= UINT_MAX returns UINT_MAX.


If UINT_MAX == ULONG_MAX then tmp>UINT_MAX can never be true and
UINT_MAX will never be returned by your function, even when
overflow occurs.


You snipped the code in question and the attributions (it wasn't
my function), but strtoul will return ULONG_MAX for an overflow,
IIRC, which in this case is == UINT_MAX, and is returned. The
code is portable.

I repeat - so?

--
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 #44
nrk
Martin wrote:
"CBFalconer " wrote:
So? As before, this means input >= UINT_MAX returns UINT_MAX.
If UINT_MAX == ULONG_MAX then tmp>UINT_MAX can never be true and UINT_MAX
will never be returned by your function, even when overflow occurs.


That would automatically be taken care of by strtoul. In case of overflow,
strtoul will return ULONG_MAX (which also happens to UINT_MAX in the
scenario you describe) and set errno to ERANGE. Richard's code takes the
extra care for situations where ULONG_MAX > UINT_MAX.

-nrk.
Martin
http://martinobrien.co.uk/


--
Remove devnull for email
Nov 14 '05 #45
RoRsOaMrPiEo <n@esiste.ee> wrote:
On Fri, 20 Feb 2004 12:32:52 GMT, rl*@hoekstra-uitgeverij.nl (Richard
Bos) wrote:
> #include <limits.h>
> #include <stdlib.h>
>
> unsigned int htoi(char *txt)
> {
> unsigned long tmp=strtoul(txt , 0, 16);
> if (tmp>UINT_MAX) return UINT_MAX;
> return tmp;
> }

but here htoi(8eeeeeeeee eeeeeeeeeeeeee) ==-1

this seems htoi(8eeeeeeeee eeeeeeeeeeeeee) == INT_MAX


Imprimis, htoi(8eeeeeeeee eeeeeeeeee) is a syntax error.
Secundis, htoi("8eeeeeeee eeeeeeeeeeee") invokes undefined behaviour for
your implementation (and thus has a license to return anything,
including garbage, and even crash the machine), and returns UINT_MAX
(not INT_MAX) for my implementation, without being undefined.


so your is htou and not htoi


If you wish. Yours doesn't read signed hex numbers, either, though, so I
fail to see the advantage of having a signed format. If you wish, you
can remove all unsigneds, use strtol() instead of strtoul(), and INT_MAX
instead of UINT_MAX, and you'll have a version which can read only half
of the original numbers but returns a signed int.

In fact, if I were you, I'd use strtoul() directly. Much simpler.
and some
slight slowness, while not ideal, is at least to be preferred above a
license to crash your machine at any inconvenient moment.


crash where in code?


Wherever it invokes undefined behaviour. I haven't checked it in detail,
but people upthread said that it does. They may, of course, have been
mistaken.

Richard
Nov 14 '05 #46
RoRsOaMrPiEo <n@esiste.ee> wrote:
is there any pc where
(int) (unsigned) INT_MAX != INT_MAX (this would be true for K&R?)
No. INT_MAX must be representable in unsigned int (6.2.5#9 in C99).
(int) (unsigned) INT_MIN != INT_MIN

or where if zE{INT_MIN...IN T_MAX}
then (int) (unsigned) z != z


Whether such a machine actually exists I don't know, but AFAICT it's
certainly allowed. Conversion of out-of-range values to unsigned format
is defined to be done modulo (<type>_MAX+1) , but conversion of out-of-
range values to signed format is not well-defined.

Richard
Nov 14 '05 #47

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
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
10289
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10061
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,...
0
8952
agi2029
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...
1
7471
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
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...
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.