Have some bugs when implementing my own Atoi() - c

I can't understand. While my function returning, from char in main, random number. Original atoi() returning -1. I'm currently using C11 version. I heard from someone, that's because of int overflow and i need return int from my function, but i'm currently returning long. How can i detect intOverflow if that's not a 2147483647
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool mx_isdigit(int c) {
return c >= 48 && c <= 57;
}
bool mx_isspace(char c) {
return (c >= 9 && c <= 13) || c == 32;
}
int mx_atoi(const char *str) {
long num = 0;
int sign = 1;
for (; mx_isspace(*str); str++);
if (*str == '-' || *str == '+') {
sign = *str == '-' ? -sign : sign;
str++;
}
for (; *str; str++) {
if (!mx_isdigit(*str)) {
break;
}
num = (num * 10) + (*str - '0');
}
return sign == -1 ? -num : 0 + num;
}
int main(void) {
char str[100] = "12327123061232712306";
printf("R: %d\n", atoi(str));
printf("M: %d", mx_atoi(str));
}

Inside your function int mx_atoi(const char *str) {..., you are calculating a result of type long, yet the function returns an int; so if the result stored in num of type long does not fit in an int, something will get lost (actually , since signed integral values are converted, the behaviour is "implementation-defined", i.e. compiler-dependant). The result could be truncated bitwise, yielding a number that "looks" rather different that the decimal number you entered. Cf., for example, this online C11 draft. The bold paragraph applies:
6.3.1.3 Signed and unsigned integers
1 When a value with integer type is converted to another integer type
other than _Bool, if the value can be represented by the new type, it
is unchanged.
2 Otherwise, if the new type is unsigned, the value is converted by
repeatedly adding or subtracting one more than the maximum value that
can be represented in the new type until the value is in the range of
the new type.60)
3 Otherwise, the new type is signed and the value cannot be
represented in it; either the result is implementation-defined or an
implementation-defined signal is raised.
Make int mx_atoi(const char *str) to long mx_atoi(const char *str), use a long-variable to store the result, and don't forget to use format specifier %ld instead of %d in your printf then.
Otherwise, if you need to stick to int and you want to safely react on overflows, you could do something like
if (num > INT_MAX) {
return -1;
}
inside your loop. INT_MAX is defined in limits.h

c >= 48 && c <= 57
Do not use magic numbers in the code. Instead of 48 use '0' which is way more readable and provides what intention your do.
How can i detect intOverflow
Overflow happens when the result is greater then the maximum a type can represent. So having numbers a and b we can write:
a + b > MAX
But such condition could not be checked, because a + b... will overflow. But if we flip the expression:
b > MAX - a
Can be easily checked with a simple if. MAX is the maximum value for a type, for int that is INT_MAX from limits.h.
int mx_atoi(const char *str) {
for (; mx_isspace(*str); str++);
bool negative = false;
if (*str == '-' || *str == '+') {
negative = *str == '-';
str++;
}
int num = 0;
for (; mx_isdigit(*str); str++) {
if (INT_MAX / 10 < num) {
goto ERR_OVERFLOW;
}
num *= 10;
const unsigned char c = *str - '0';
if (INT_MAX - c < num) {
goto ERR_OVERFLOW;
}
num += c;
}
return negative ? -num : num;
ERR_OVERFLOW:
return negative ? INT_MIN : INT_MAX;
}

int overflow potential
num = (num * 10) + (*str - '0'); encounters int overflow, which is undefined behavior (UB) when:
1) input string should represent INT_MIN and int/long have the same range OR
2) input string encodes a value outside the int range.
Various ways to avoid that.
Does not detect a string of no digits
Returning 0 in that case is reasonable, yet code may want to set some error condition.
Does not complain about trailing non-digits
Simply ignoring trailing characters is reasonable, yet code may want to set some error condition.
A way to avoid int overflow (and not rely on long wider than int) is to test before (num * 10) + (*str - '0') and since there is more negative ints than positive ones, accumulate on the negative side.
bool digit_found = false;
int val = 0;
for (; mx_isdigit(*str); str++) {
digit_found = true;
int digit = *str - '\0';
if (val <= INT_MIN/10 && (val < INT_MIN/10 || digit > -(INT_MIN%10))) { // C99
return sign == 1 ? INT_MAX : INT_MIN;
}
val = val * 10 - digit; // note subtraction here
}
if (!digit_found) {
return 0; // Or handle in some other fashion
}
if (sign == 1) {
// If val is too negative to negate ...
if (val < -INT_MAX) {
return INT_MAX; // overflow
}
return -val;
}
return val;

This is the easiest way, that i guessed. atoi() original using LLONG_MAX check instead of LONG_MAX or INT_MAX. So, experimenting with those limits i discovered. That if (num * 10) + (*str - '0') will reach over the limit of long long type, it will transform number to negative value of LLONG_MIN. So, i have created if statement, that check if next calculation will be less than previous. And if it's true, returning 0 or -1.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
bool mx_isdigit(int c);
bool mx_isspace(char c);
int mx_atoi(const char* str) {
long long num = 0;
int sign = 1;
for (; mx_isspace(*str); str++);
if (*str == '-' || *str == '+') {
sign = *str == '-' ? -sign : sign;
str++;
}
for (; *str; str++) {
if (!mx_isdigit(*str)) {
break;
}
if ((num * 10) + (*str - '0') < num) {
return sign == -1 ? 0 : -1;
}
num = (num * 10) + (*str - '0');
}
return sign == -1 ? -num : num;
}
int main(void) {
char str[100] = "-9223372036854775809";
printf("R: %d\n", atoi(str));
printf("M: %d\n", mx_atoi(str));
}

Related

Long Long overflow

I have been working on a small program that converts strings into integers.
I started the program and I was first trying to save in an array but the program is not working.
Its iterating only once and there is no error.I tried it but I think the error is at when I convert the string by subtracting it by 48 in storing it in the array.You can see the code
Sorry this is an edited message tnow the program is working properly but when I give input -"-91283472332"(as per leetcode) I am getting a wrong answer
you can see for yourself -
#include <stdio.h>
int myAtoi(char *s)
{
int i = 0; // for iterating the character
int isNegative = 0; // for checking if the umber is negative
long long res = 0; // for result
while (s[i] != '\0')
{
printf("%d\n",res);
if (48 <= s[i] && s[i]<= 57)
{
res=(res*10)+(s[i]) - 48;
}
else if (s[i] == 45)
{
isNegative = 1;
}
else if (s[i] == ' ')
{
;
}
else
{
break;
}
i++;
}
if (isNegative)
{
res = res-(res*2);
}
printf("%d",res);
return res;
}
int main()
{
char a[] = "-91283472332";
myAtoi(a);
return 0;
}
Your solution is rather more complex than it needs to be.
We can use pointer arithmetic to iterate over the string, and include a condition for our for loop that automatically terminates at the end of the string or when the current character is no longer a digit.
The result can be built up by multiplying it by ten on each loop and adding the current digit's numeric value to it.
A negative sign can be accommodated by checking the first character. It's it's '-' we can set a flag negative to 1 for true and increment the str pointer past the first character. At the end of the function, we can determine whether to result -result or result based on that flag.
#include <string.h>
#include <stdio.h>
#include <ctype.h>
int my_atoi(char *str) {
int result = 0;
int negative = 0;
if (*str == '-') {
negative = 1;
str++;
}
for (; *str && isdigit(*str); str++) {
result *= 10;
result += *str - '0';
}
return negative ? -result : result;
}
int main(void) {
char foo[] = "3456gfghd";
printf("%d\n", my_atoi(foo));
return 0;
}

How do I check the first two characters of my char array in C?

This is code to create a similar C library function atoi() without the use of any C runtime library routines.
I'm currently stuck on how to check for the first two digits of the char array s to see whether the input begins with "0x".
If it starts with 0x, this means that I can then convert it in to hexadecimal.
#include <stdio.h>
int checkforint(char x){
if (x>='0' && x<='9'){
return 1;
}
else{
return 0;
}
}
unsigned char converthex(char x){
//lets convert the character to lowercase, in the event its in uppercase
x = tolower(x);
if (x >= '0' && x<= '9') {
return ( x -'0');
}
if (x>='a' && x<='f'){
return (x - 'a' +10);
}
return 16;
}
int checkforhex(const char *a, const char *b){
if(a = '0' && b = 'x'){
return 1;
}else{
return 0;
}
}
//int checkforint
/* We read an ASCII character s and return the integer it represents*/
int atoi_ex(const char*s, int ishex)
{
int result = 0; //this is the result
int sign = 1; //this variable is to help us deal with negative numbers
//we initialise the sign as 1, as we will assume the input is positive, and change the sign accordingly if not
int i = 0; //iterative variable for the loop
int j = 2;
//we check if the input is a negative number
if (s[0] == '-') { //if the first digit is a negative symbol
sign = -1; //we set the sign as negative
i++; //also increment i, so that we can skip past the sign when we start the for loop
}
//now we can check whether the first characters start with 0x
if (ishex==1){
for (j=2; s[j]!='\0'; ++j)
result = result + converthex(s[j]);
return sign*result;
}
//iterate through all the characters
//we start from the first character of the input and then iterate through the whole input string
//for every iteration, we update the result accordingly
for (; s[i]!='\0'; ++i){
//this checks whether the current character is an integer or not
//if it is not an integer, we skip past it and go to the top of the loop and move to the next character
if (checkforint(s[i]) == 0){
continue;
} else {
result = result * 10 + s[i] -'0';
}
//result = s[i];
}
return sign * result;
}
int main(int argc)
{
int isithex;
char s[] = "-1";
char a = s[1];
char b = s[2];
isithex=checkforhex(a,b);
int val = atoi_ex(s,isithex);
printf("%d\n", val);
return 0;
}
There are several errors in your code. First, in C you start counting from zero. So in main(), you should write:
char a = s[0];
char b = s[1];
isithex = checkforhex(a, b);
Then, in checkforhex(), you should use == (two equal signs) to do comparisons, not =. So:
if (a == '0' && b == 'x')
However, as pointed out by kaylum, why not write the function to pass a pointer to the string instead of two characters? Like so:
int checkforhex(const char *str) {
if (str[0] == '0' && str[1] == 'x') {
...
}
}
And in main() call it like so:
isithex = checkforhex(s);

Decimal to Binary in C

I'm creating a program that adds and subtracts 2 numbers. Then I have to output this answer into different bases.
My answer is in decimal format, of type long double, such as:
long double answer;
answer = numberOne + numberTwo;
I want to convert this answer into binary. Now I have code used earlier in my program that does this, but with a char pointer:
char * decimalBinary (char * decimalNumber)
{
bool zeroFront = true;
int i;
int z;
int j = 0;
int n = atoi(decimalNumber);
char * binaryNum = malloc(32+1);
binaryNum[32] = '\0';
int current_index=1;
int end_index = strlen(decimalNumber)-1;
//Error check for valid decimal input, needed error check for beginning of code
while(current_index <= end_index)
{
if(decimalNumber[current_index] != '0' &&decimalNumber[current_index] != '1' &&decimalNumber[current_index] != '2' &&decimalNumber[current_index] != '3' &&decimalNumber[current_index] != '4' &&decimalNumber[current_index] != '5' &&dec[current_index] != '6' &&dec[current_index] != '7' &&decimalNumber[current_index] != '8' &&decimalNumber[current_index] != '9')
{
binaryNum[0] = -8;
return binaryNum;
}
current_index++;
}
for (i = 31; i >= 0; i--) {
z = n >> i;
if (z & 1)
{
binaryNum[j] = '1';
j++;
zeroFront = false;
}
else if (!zeroFront)
{
binaryNum[j] = '0';
j++;
}
}
binaryNum[j] = '\0';
return binaryNum;
}
My preferred solution is to use the code I already have in my program to convert my answer into a binary format, but as you can see the parameters are conflicting, and I'm not sure how to go about doing that.
Another possible solution that detracts from having reusable code in my program, is to create a different function all together that converts a decimal to a binary, but accepting a parameter of type long double, which is a bit unclear to me as well.
Edit:
Instead of long double, my answer is of type int.
If you really want to reuse your function without modifications, you can transform answer into a decimal string and pass the string to your function.
char stringAnswer[20];
sprintf(stringAnswer, "%d", answer);
printf("the binary answer is %s\n", decimalBinary(stringAnswer));
But a better solution should be to split the function decimalBinary into two functions : the first one to check that all digits are ok, and the second one to convert a int into a binary string.
Then you'll be able to call directly this second function with answer as parameter.
Rather than use a magic number 32, better to let the compiler deduce the needed size as an int is not always 32 bits. Checking allocation results is a good habit.
#include <assert.h>
#include <stdlib.h>
#define INT_MAX_BIN_WIDTH (sizeof(int) * CHAR_BIT)
char * binaryNum = malloc(INT_MAX_BIN_WIDTH+1);
assert(binaryNum != NULL);
binaryNum[INT_MAX_BIN_WIDTH] = '\0'; // null character
Rather than checking against each digit, since '0' to '9' must be sequential:
// if(decimalNumber[current_index] != '0' &&decimalNumber[current_index] != '1' ...
if (decimalNumber[current_index] < '0' || decimalNumber[current_index] >= '9') ...
// or
if (!isdigit((unsigned char) decimalNumber[current_index])) ...
Problem does not address negative numbers. Better to state that they will not occur or better, make code handle them.
Code allocates memory, but does not free it. Consider letting the higher level code allocate/free and supply the needed buffer to decimalBinary(char *dest, size_t size, const char *src). Robust code would supply the size too.
char *binaryNum = malloc(INT_MAX_BIN_WIDTH+1);
assert(binaryNum != NULL);
decimalBinary(binaryNum, INT_MAX_BIN_WIDTH+1, "123");
do_something(binaryNum);
free(binaryNum);
Following is a solution that is not limited to 32 bits. It does not cope with negative numbers nor memory allocation - certainly it should provide some ideas for your eventual solution.
#include <stdio.h>
#include <string.h>
static void times10(char *binaryNumber, int carry) {
size_t length = strlen(binaryNumber);
size_t i = length;
while (i > 0) {
i--;
int sum = (binaryNumber[i] - '0') * 10 + carry;
binaryNumber[i] = sum % 2 + '0';
carry = sum / 2;
}
while (carry) {
memmove(&binaryNumber[1], &binaryNumber[0], ++length);
binaryNumber[0] = carry % 2 + '0';
carry /= 2;
}
}
char *decimalBinary(char *binaryNumber, const char *decimalNumber) {
strcpy(binaryNumber, "0");
int ch;
while ((ch = *decimalNumber++) >= '0' && (ch <= '9')) {
times10(binaryNumber, ch - '0');
}
return binaryNumber;
}
int main(void) {
char buf10[200];
puts(decimalBinary(buf10, "123"));
puts(decimalBinary(buf10, "123456"));
puts(decimalBinary(buf10, "123456789012345678901234567890"));
return 0;
}

Recursive function to convert string to integer in C

I have the following working code; it accepts a string input as the function parameter and spits out the same string converted to a decimal.
I'm not going to bother accounting for negative inputs, although I understand that I can set a boolean flag to true when the first indexed character is a "-". If the flag switches to true, take the total output and multiply by -1.
Anyway, I'm pretty stuck on where to go from here; I'd like to adjust my code so that I can account for a decimal place. Multiplying by 10 and adding the next digit (after converting that digit from an ASCII value) yields an integer that is displayed in decimal in the output. This obviously won't work for numbers that are smaller than 1. I understand why (but not really how) to identify where the decimal point is and say that "for anything AFTER this string index containing a decimal point, do this differently"). Also, I know that instead of multiplying by a power of 10 and adding the next number, I have to multiply by a factor of -10, but I'm not sure how this fits into my existing code...
#include <stdio.h>
#include <string.h>
int num = 0;
int finalValue(char *string1) {
int i = 0;
if (string1[i] != '\0') {
if (string1[i]<'0' || string1[i]>'9') {
printf("Sorry, we can't convert this to an integer\n\n");
}
else {
num *= 10;
num += string1[i] - '0';
//don't bother using a 'for' loop because recursion is already sort-of a for loop
finalValue(&string1[i+1]);
}
}
return num;
}
int main(int argc, const char * argv[]) {
printf("string to integer conversion yields %i\n",(finalValue("99256")));
return 0;
}
I made some adjustments to the above code and it works, but it's a little ugly when it comes to the decimal part. For some reason, the actual integer output is always higher than the string put in...the math is wrong somewhere. I accounted for that by subtracting a static amount (and manually multiplying by another negative power of 10) from the final return value...I'd like to avoid doing that, so can anybody see where my math / control flow is going wrong?
#include <stdio.h>
#include <string.h>
//here we are setting up a boolean flag and two variables
#define TRUE 1
#define FALSE 0
double num = 0;
double dec = 0.0;
int flag = 0;
double final = 0.0;
double pow(double x, double y);
//we declare our function that will output a DOUBLE
double finalValue(char *string1) {
//we have a variable final that we will return, which is just a combination of the >1 and <1 parts of the float.
//i and j are counters
int i = 0;
int j = 0;
//this will go through the string until it comes across the null value at the very end of the string, which is always present in C.
if (string1[i] != '\0') {
//as long as the current value of i isn't 'null', this code will run. It tests to see if a flag is true. If it isn't true, skip this and keep going. Once the flag is set to TRUE in the else statement below, this code will continue to run so that we can properly convert the decimal characers to floats.
if (flag == TRUE) {
dec += ((string1[i] - '0') * pow(10,-j));
j++;
finalValue(&string1[i+1]);
}
//this will be the first code to execute. It converts the characters to the left of the decimal (greater than 1) to an integer. Then it adds it to the 'num' global variable.
else {
num *= 10;
num += string1[i] - '0';
// This else statement will continue to run until it comes across a decimal point. The code below has been written to detect the decimal point and change the boolean flag to TRUE when it finds it. This is so that we can isolate the right part of the decimal and treat it differently (mathematically speaking). The ASCII value of a '.' is 46.
//Once the flag has been set to true, this else statement will no longer execute. The control flow will return to the top of the function, and the if statement saying "if the flag is TRUE, execute this' will be the only code to run.
if (string1[i+1] == '.'){
flag = TRUE;
}
//while this code block is running (before the flag is set to true) use recursion to keep converting characters into integers
finalValue(&string1[i+1]);
}
}
else {
final = num + dec;
return final;
}
return final;
}
int main(int argc, const char * argv[]) {
printf("string to integer conversion yields %.2f\n",(finalValue("234.89")));
return 0;
}
I see that you have implemented it correctly using global variables. This works, but here is an idea on how to avoid global variables.
A pretty standard practice is adding parameters to your recursive function:
double finalValue_recursive(char *string, int flag1, int data2)
{
...
}
Then you wrap your recursive function with additional parameters into another function:
double finalValue(char *string)
{
return finalValue_recursive(string, 0, 0);
}
Using this template for code, you can implement it this way (it appears that only one additional parameter is needed):
double finalValue_recursive(char *s, int pow10)
{
if (*s == '\0') // end of line
{
return 0;
}
else if (*s == '-') // leading minus sign; I assume pow10 is 0 here
{
return -finalValue_recursive(s + 1, 0);
}
else if (*s == '.')
{
return finalValue_recursive(s + 1, -1);
}
else if (pow10 == 0) // decoding the integer part
{
int digit = *s - '0';
return finalValue_recursive(s + 1, 0) * 10 + digit;
}
else // decoding the fractional part
{
int digit = *s - '0';
return finalValue_recursive(s + 1, pow10 - 1) + digit * pow(10.0, pow10);
}
}
double finalValue(char *string)
{
return finalValue_recursive(string, 0);
}
Also keep track of the occurrence of the decimal point.
int num = 0;
const char *dp = NULL;
int dp_offset = 0;
int finalValue(const char *string1) {
int i = 0;
if (string1[i] != '\0') {
if (string1[i]<'0' || string1[i]>'9') {
if (dp == NULL && string1[i] == '.') {
dp = string1;
finalValue(&string1[i+1]);
} else {
printf("Sorry, we can't convert this to an integer\n\n");
} else {
} else {
num *= 10;
num += string1[i] - '0';
finalValue(&string1[i+1]);
}
} else if (dp) {
dp_offset = string1 - dp;
}
return num;
}
After calling finalValue() code can use the value of dp_offset to adjust the return value. Since this effort may be the beginning of a of a complete floating-point conversion, the value of dp_offset can be added to the exponent before begin applied to the significand.
Consider simplification
//int i = 0;
//if (string1[i] ...
if (*string1 ...
Note: using recursion here to find to do string to int is a questionable approach especially as it uses global variables to get the job done. A simply function would suffice. Something like untested code:
#include <stdio.h>
#include <stdlib.h>
long long fp_parse(const char *s, int *dp_offset) {
int dp = '.';
const char *dp_ptr = NULL;
long long sum = 0;
for (;;) {
if (*s >= '0' && *s <= '9') {
sum = sum * 10 + *s - '0';
} else if (*s == dp) {
dp_ptr = s;
} else if (*s) {
perror("Unexpected character");
break;
} else {
break;
}
s++;
}
*dp_offset = dp_ptr ? (s - dp_ptr -1) : 0;
return sum;
}
Figured it out:
#include <stdio.h>
#include <string.h>
//here we are setting up a boolean flag and two variables
#define TRUE 1
#define FALSE 0
double num = 0;
double dec = 0.0;
int flag = 0;
double final = 0.0;
double pow(double x, double y);
int j = 1;
//we declare our function that will output a DOUBLE
double finalValue(char *string1) {
//i is a counter
int i = 0;
//this will go through the string until it comes across the null value at the very end of the string, which is always present in C.
if (string1[i] != '\0') {
double newGuy = string1[i] - 48;
//as long as the current value of i isn't 'null', this code will run. It tests to see if a flag is true. If it isn't true, skip this and keep going. Once the flag is set to TRUE in the else statement below, this code will continue to run so that we can properly convert the decimal characers to floats.
if (flag == TRUE) {
newGuy = newGuy * pow(10,(j)*-1);
dec += newGuy;
j++;
finalValue(&string1[i+1]);
}
//this will be the first code to execute. It converts the characters to the left of the decimal (greater than 1) to an integer. Then it adds it to the 'num' global variable.
else {
num *= 10;
num += string1[i] - '0';
// This else statement will continue to run until it comes across a decimal point. The code below has been written to detect the decimal point and change the boolean flag to TRUE when it finds it. This is so that we can isolate the right part of the decimal and treat it differently (mathematically speaking). The ASCII value of a '.' is 46.
//Once the flag has been set to true, this else statement will no longer execute. The control flow will return to the top of the function, and the if statement saying "if the flag is TRUE, execute this' will be the only code to run.
if (string1[i+1] == 46){
flag = TRUE;
finalValue(&string1[i+2]);
}
//while this code block is running (before the flag is set to true) use recursion to keep converting characters into integers
finalValue(&string1[i+1]);
}
}
else {
final = num + dec;
return final;
}
return final;
}
int main(int argc, const char * argv[]) {
printf("string to integer conversion yields %.2f\n",(finalValue("234.89")));
return 0;
}

Questions about a Kernighan and Ritchie Excercise 2-3

I'm trying to write a program in C that converts hexadecimal numbers to integers. I've written successfully a program that converts octals to integers. However, the problems begin once I start using the letters (a-f). My idea for the program is ads follows:
The parameter must be a string that starts with 0x or 0X.
The parameter hexadecimal number is stored in a char string s[].
The integer n is initialized to 0 and then converted as per the rules.
My code is as follows (I've only read up to p37 of K & R so don't know much about pointers) :
/*Write a function htoi(s), which converts a string of hexadecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F.*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
int htoi(const char s[]) { //why do I need this to be constant??
int i;
int n = 0;
int l = strlen(s);
while (s[i] != '\0') {
if ((s[0] == '0' && s[1] == 'X') || (s[0] == '0' && s[1] == 'x')) {
for (i = 2; i < (l - 1); ++i) {
if (isdigit(s[i])) {
n += (s[i] - '0') * pow(16, l - i - 1);
} else if ((s[i] == 'a') || (s[i] == 'A')) {
n += 10 * pow(16, l - i - 1);
} else if ((s[i] == 'b') || (s[i] == 'B')) {
n += 11 * pow(16, l - i - 1);
} else if ((s[i] == 'c') || (s[i] == 'C')) {
n += 12 * pow(16, l - i - 1);
} else if ((s[i] == 'd') || (s[i] == 'D')) {
n += 13 * pow(16, l - i - 1);
} else if ((s[i] == 'e') || (s[i] == 'E')) {
n += 14 * pow(16, l - i - 1);
} else if ((s[i] == 'f') || (s[i] == 'F')) {
n += 15 * pow(16, l - i - 1);
} else {
;
}
}
}
}
return n;
}
int main(void) {
int a = htoi("0x66");
printf("%d\n", a);
int b = htoi("0x5A55");
printf("%d\n", b);
int c = htoi("0x1CA");
printf("%d\n", c);
int d = htoi("0x1ca");
printf("%d\n", d);
}
My questions are:
1. If I don't use const in the argument for htoi(s), i get the following warnings from the g++ compiler :
2-3.c: In function ‘int main()’: 2-3.c:93:20: warning: deprecated
conversion from string constant to ‘char*’ [-Wwrite-strings]
2-3.c:97:22: warning: deprecated conversion from string constant to
‘char*’ [-Wwrite-strings] 2-3.c:101:21: warning: deprecated conversion
from string constant to ‘char*’ [-Wwrite-strings] 2-3.c:105:21:
warning: deprecated conversion from string constant to ‘char*’
[-Wwrite-strings]
Why is this?
2.Why is my program taking so much time to run? I haven't seen the results yet.
3.Why is it that when I type in cc 2-3.c instead of g++ 2-3.c in the terminal, I get the following error message:
"undefined reference to `pow'"
on every line that I've used the power function?
4. Please do point out other errors/ potential improvements in my program.
If I don't use const in the argument for htoi(s), i get the following warnings from the g++ compiler
The const parameter should be there, because it is regarded as good and proper programming to never typecast away const from a pointer. String literals "..." should be treated as constants, so if you don't have const as parameter, the compiler thinks you are casting away the const qualifier.
Furthermore, you should declare all pointer parameters that you don't intend to modify the contents of as const, Google the term const correctness.
Why is my program taking so much time to run? I haven't seen the results yet.
I think mainly because you have made an initialization goof-up. int i; i contains rubbish. Then while (s[rubbish_value] != '\0'). This function can be written a whole lot better too. Start by checking for the 0x in the start of the string, if they aren't there, signal some error (return NULL?), otherwise discard them. Then start one single loop after that, you don't need 2 loops.
Note that the pow() function deals with float numbers, which will make your program a slight bit slower. You could consider using an integer-only version. Unfortunately there is no such function in standard C, so you will have to found one elsewhere.
Also consider the function isxdigit(), a standard function in ctype.h, which checks for digits 0-9 as well as hex letters A-F or a-f. It may however not help with performance, as you will need to perform different calculations for digits and letters.
For what it is worth, here is a snippet showing how you can convert a single char to a hexadecimal int. It is not the most optimized version possible, but it takes advantage of available standard functions, for increased readability and portability:
#include <ctype.h>
uint8_t hexchar_to_int (char ch)
{
uint8_t result;
if(isdigit(ch))
{
result = ch - '0';
}
else if (isxdigit(ch))
{
result = toupper(ch) - 'A' + 0xA;
}
else
{
// error
}
return result;
}
Don't use a C++ compiler to compile a C program. That's my first advice to you.
Secondly const in a function parameter for a char * ensures that the programmer doesn't accidentally modify the string.
Thirdly you need to include the math library with -lm as stated above.
a const char[] means that you cannot change it in the function. Casting from a const to not-const gives a warning. There is much to be said about const. Check out its Wikipedia page.
--
Probably, cc doesn't link the right libraries. Try the following build command: cc 2-3.c -lm
Improvements:
Don't use pow(), it is quite expensive in terms of processing time.
Use the same trick with the letters as you do with the numbers to get the value, instead of using fixed 'magic' numbers.
You don't need the last else part. Just leave it empty (or put an error message there, because those characters aren't allowed).
Good luck!
About my remark about the pow() call (with the use of the hexchar_to_int() function described above, this is how I'd implement this (without error checking):
const char *t = "0x12ab";
int i = 0, n = 0;
int result = 0;
for (i = 2; i < strlen(t); i++) {
n = hexchar_to_int(t[i]);
result |= n;
result <<= 4;
}
/* undo the last shift */
result >>= 4;
I just worked through this exercise myself, and I think one of the main ideas was to use the knowledge that chars can be compared as integers (they talk about this in chapter 2).
Here's my function for reference. Thought it may be useful as the book doesn't contain answers to exercises.
int htoi(char s[]) {
int i = 0;
if(s[i] == '0') {
++i;
if(s[i] == 'x' || s[i] == 'X') {
++i;
}
}
int val = 0;
while (s[i] != '\0') {
val = 16 * val;
if (s[i] >= '0' && s[i] <= '9')
val += (s[i] - '0');
else if (s[i] >= 'A' && s[i] <= 'F')
val += (s[i] - 'A') + 10;
else if (s[i] >= 'a' && s[i] <= 'f')
val += (s[i] - 'a') + 10;
else {
printf("Error: number supplied not valid hexadecimal.\n");
return -1;
}
++i;
}
return val;
}
Always init your variables int i=0, otherwise i will contain a garbage value, could be any number, not necessary 0 as you expect. You're running the while statement in an infinite loop, that's why it takes forever to get the results, print i to see why. Also, add a break if the string doesn't start with 0x, will avoid the same loop issue when the user is used on a random string. As others mention you need to import the library containing pow function and declare your string with const to get rid of the warning.
This is my version of program for the question above. It converts the string of hex into decimal digits irrespective of optional prefix(0x or 0X).
4 important library functions used are strlen(s), isdigit(c), isupper(c), isxdigit(c), pow(m,n)
Suggestions to improve the code are welcome :)
/*Program - 5d Function that converts hex(s)into dec -*/
#include<stdio.h>
#include<stdlib.h>
#include<math.h> //Declares mathematical functions and macros
#include<string.h> //Refer appendix in Page 249 (very useful)
#define HEX_LIMIT 10
int hex_to_dec(char hex[]) //Function created by me :)
{
int dec = 0; //Initialization of decimal value
int size = strlen(hex); //To find the size of hex array
int temp = size-1 ; //Pointer pointing the right element in array
int loop_limit = 0; //To exclude '0x' or 'OX' prefix in input
if(hex[0]=='0' && ((hex[1]=='x') || (hex[1]=='X')))
loop_limit = 2;
while(temp>=loop_limit)
{
int hex_value = 0; //Temporary value to hold the equivalent hex digit in decimal
if(isdigit(hex[temp]))
hex_value = (hex[(temp)]-'0') ;
else if(isxdigit(hex[temp]))
hex_value = (toupper(hex[temp])-'A' + 10);
else{
printf("Error: No supplied is not a valid hex\n\n");
return -1;
}
dec += hex_value * pow(16,(size-temp-1)); //Computes equivalent dec from hex
temp--; //Moves the pointer to the left of the array
}
return dec;
}
int main()
{
char hex[HEX_LIMIT];
printf("Enter the hex no you want to convert: ");
scanf("%s",hex);
printf("Converted no in decimal: %d\n", hex_to_dec(hex));
return 0;
}

Resources