Skip to content

Update 3.atoi.c #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions chapter-2-types-operators-expressions/3.atoi.c
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
#include <stdio.h>

int atoi(char[]);
int htoi(char[]);

main()
{
int a = atoi("1234567890");
printf("%d\n", a);
a = atoi("1234abc567890");
printf("%d\n", a);

//repeat lines 10 and 11 using htoi
a = htoi("1234abc567890");
printf("%d\n", a);
}

int atoi(char s[])
@@ -18,3 +23,31 @@ int atoi(char s[])
n = 10 * n + (s[i] - '0');
return n;
}

/*
Function htoi should return hexadecimal form. Current function atoi returns only decimal form
For example, line 10 (originally at line 9) returns a value of 1234 rather than the correct decimal value of 320278871046288.
See function below. In current form, return is an int, can also be a long double to support larger inputs
*/

int htoi(char s[])
{
int i;
long double n;

n = 0;
for (i = 0; (s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f') || (s[i] >= 'A' && s[i] <= 'F'); ++i)
{
if (i == 0 && s[i] == '0')
i = 2;
else if (s[i] >= '0' && s[i] <= '9')
n = 16 * n + (s[i] - '0');
else if (s[i] >= 'a' && s[i] <= 'f')
n = 16 * n + (s[i] - 'a' + 10.0);
else
n = 16 * n + (s[i] - 'A' + 10.0);
}
return n;
}