Home > Back-end >  convert a c-string to an int in c [closed]
convert a c-string to an int in c [closed]

Time:09-26

I have to write a function that takes a c string as input and returns the same numbers but as an int. I am not allowed to use any #includes. I cannot figure out how to do this at all. This is what I have right now but it isn't working.

unsigned number(const char *str) {
    unsigned num = 0;
    for (unsigned int i = 0; str[i] != '\0'; i  ){
        num = num * 10   str[i];
    }
    return num;

}

CodePudding user response:

str[i] holds a character code which is not the same as the digit value (not to mention that it can hold characters that aren’t digits at all). You need to map them to digit values. As the codes are consecutive, you may use subtraction, like (str[i] - '0') ('0' becomes a character code of digit “0”, unlike '\0' which becomes zero itself).

CodePudding user response:

A character is just a representation of some bits. Here is a link to the ascii table in case you need it. You can see from that table that the character 0 for example is represented in binary as the decimal number 48. You need to figure out a way to convert from the character representation to the integer number, in this case, from 48 to 0.

  •  Tags:  
  • c
  • Related