What is String to Integer in C- Best Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Strings · Lecture 38

String to Integer in C

Write your own safe atoi: handle signs, spaces, bad input and overflow. Essential embedded C programming skill from our free C tutorial.

Every command line, configuration file, serial console and protocol field arrives as text. To use it, you must convert a string to an integer in C. The standard atoi looks convenient, but it cannot tell you when something went wrong. In this lecture of our free C programming course you will write your own converter that rejects bad input and detects overflow, and you will see exactly why that matters in embedded C programming, where a mis-parsed value can drive a motor, a heater or a bootloader command. This is part of our free embedded C course for students and working engineers.

What You Will Learn

  • How decimal digits are turned into a value one character at a time
  • Why ch - '0' is the correct way to get a digit value
  • How to handle leading spaces, plus and minus signs
  • How to detect empty input, trailing junk and overflow
  • Why a status code beats a magic return value
  • How this compares with atoi and strtol

Prerequisites

You should know character arithmetic, loops over strings, pointers to char and enumerations. Earlier lectures in this free C programming course cover each of these.

How Digits Become a Number

The text “472” is three separate characters. The program builds the value by repeating one rule: multiply what you have so far by 10, then add the next digit. Starting from zero:

Building 472 from the characters ‘4’, ‘7’, ‘2’

startvalue = 0
read ‘4’0 x 10 + 4value = 4
read ‘7’4 x 10 + 7value = 47
read ‘2’47 x 10 + 2value = 472

Getting the Digit Value

The digit characters ‘0’ to ‘9’ have consecutive codes in every C implementation, as the C standard requires. So ch - '0' gives 0 to 9. Writing '0' instead of the magic number 48 makes the code readable and correct on any character set.

What Can Go Wrong with Text Input

InputProblemWhat a good parser does
" +7"leading spaces and an explicit plusskip spaces, accept the sign
"12ab"digits followed by junkreport a bad character
"" or "-"no digits at allreport empty input
"2147483648"too large for a 32-bit intreport overflow
"-2147483648"smallest legal intaccept it

Warning: signed overflow is undefined behaviour in C. If you keep multiplying an int past its limit, the compiler is allowed to assume it never happens, and your program can misbehave in surprising ways. Detect the problem before it happens, or accumulate in a wider type and check.

Design of a Safe String to Integer Function

The function returns a status code and writes the value through a pointer. This is a common embedded pattern because every possible return value of an int is a legitimate number, so there is no spare value to signal an error. We accumulate in a long long, which is wide enough to hold any 32-bit value plus one extra digit, and we stop as soon as the running total exceeds INT_MAX + 1.

The Complete Program

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

enum parse_status { PARSE_OK = 0, PARSE_EMPTY, PARSE_BAD_CHAR, PARSE_OVERFLOW };

enum parse_status parse_int(const char *s, int *out)
{
    long long acc = 0;
    int neg = 0, digits = 0;

    while (isspace((unsigned char)*s))
        s++;
    if (*s == '-' || *s == '+')
        neg = (*s++ == '-');

    for (; *s >= '0' && *s <= '9'; s++) {
        acc = acc * 10 + (*s - '0');
        digits++;
        if (acc > (long long)INT_MAX + 1)   /* stop before long long can wrap */
            return PARSE_OVERFLOW;
    }
    if (digits == 0)
        return PARSE_EMPTY;
    if (*s != '\0')
        return PARSE_BAD_CHAR;

    if (neg)
        acc = -acc;
    if (acc > INT_MAX || acc < INT_MIN)
        return PARSE_OVERFLOW;
    *out = (int)acc;
    return PARSE_OK;
}

int main(void)
{
    const char *inputs[] = {"123", "-45", "  +7", "007", "12ab", "", "-",
                            "2147483647", "-2147483648", "2147483648", "99999999999999999999"};
    static const char *const names[] = {"ok", "empty", "bad char", "overflow"};

    for (size_t i = 0; i < sizeof inputs / sizeof inputs[0]; i++) {
        int v = 0;
        enum parse_status st = parse_int(inputs[i], &v);
        if (st == PARSE_OK)
            printf("\"%s\" -> %d (%s)\n", inputs[i], v, names[st]);
        else
            printf("\"%s\" -> rejected (%s)\n", inputs[i], names[st]);
    }
    printf("atoi(\"12ab\") quietly gives %d\n", atoi("12ab"));
    return 0;
}

Build and Run

$ gcc -std=c11 -Wall -Wextra -o parse parse.c
$ ./parse

Expected Output

"123" -> 123 (ok)
"-45" -> -45 (ok)
"  +7" -> 7 (ok)
"007" -> 7 (ok)
"12ab" -> rejected (bad char)
"" -> rejected (empty)
"-" -> rejected (empty)
"2147483647" -> 2147483647 (ok)
"-2147483648" -> -2147483648 (ok)
"2147483648" -> rejected (overflow)
"99999999999999999999" -> rejected (overflow)
atoi("12ab") quietly gives 12

Walking Through the Code

Skipping Spaces and Reading the Sign

The first loop skips whitespace. Then one optional sign character is consumed; the expression neg = (*s++ == '-') records whether it was a minus and moves on in a single step. The cast to unsigned char in isspace avoids undefined behaviour for negative character values.

Accumulating the Digits

Each digit does acc = acc * 10 + digit. After every step we compare against INT_MAX + 1. We allow exactly one more than INT_MAX because the magnitude of the most negative int, 2147483648, is one larger than the largest positive int. Anything beyond that is rejected immediately, so acc itself can never overflow, even for a 20-digit input.

Final Checks

If no digit was read, the input was empty or just a sign. If we stopped on something that is not the terminating NUL, there is trailing junk. Only then do we apply the sign and make the final range check. This order means every failure has its own clear status.

atoi, strtol and Your Own Parser

Featureatoistrtolparse_int above
Detects no digitsno (returns 0)yes (via end pointer)yes
Detects trailing junknoyes (via end pointer)yes
Detects overflowno (undefined)yes (errno and LONG_MAX)yes
Supports other basesnoyes (2 to 36)decimal only
Needs the C libraryyesyesonly ctype

In production code on a hosted system, strtol is usually the right tool. Writing your own, as we did here, teaches you what strtol does and is useful on tiny bare-metal targets where you want a small, predictable function.

Tip

On a bare-metal target, writing a parser like this avoids pulling in large library code and gives you the exact error behaviour you need for a command shell.

Real-World Use Cases

  • Serial command shells: parsing “set speed 1200” typed over a UART.
  • Configuration files: reading numeric settings from text.
  • AT commands: modems and Bluetooth modules reply with numbers inside text lines.
  • Test tools: reading expected values from a command-line argument.

Security Considerations

Any text that comes from outside your device is untrusted. A parser that accepts “12ab” as 12, or wraps around on a huge number, can turn a harmless-looking input into a wrong setpoint or a buffer size that is too small. Strict parsing with explicit failure is one of the cheapest security measures you can add to firmware.

Common Mistakes

  • Using atoi and trusting the result. It returns 0 for both “0” and “hello”.
  • Subtracting 48 instead of '0', which hides the intent.
  • Ignoring overflow. A 12-digit input silently wraps.
  • Not handling the minus sign or forgetting that INT_MIN has no positive counterpart.
  • Forgetting the empty string. It must not be accepted as zero.

Best Practices

  • Return a status and pass the value out through a pointer.
  • Reject any input that is not fully consumed.
  • Test with empty text, only a sign, the largest and smallest legal values, and one past each.
  • Prefer strtol when a full C library is available and document the choice.

Suggested Images

Image ideaSuggested ALT text
Step-by-step value building for a three digit numberstring to integer in C step by step, free C programming course
Table of good and bad inputs with resultssafe atoi alternative in C, free C tutorial for embedded C programming
Serial terminal sending a numeric commandparsing numbers from UART text in embedded C, free embedded C course

Summary and Key Takeaways

  • A number is built by multiplying by 10 and adding ch - '0' for each digit.
  • Good parsers handle spaces, signs, empty input, trailing junk and overflow.
  • Signed overflow is undefined, so check before it happens.
  • Status codes are clearer than special return values.
  • Use strtol when you can; write your own when you must.

Conclusion

You can now convert a string to an integer in C without trusting the input blindly. This careful style is what separates classroom code from firmware that survives real-world data. In the next lecture of our free embedded C course we do the reverse: turning integers into text in any base.

Frequently Asked Questions

Why is atoi considered unsafe?

It gives no way to tell bad input from a real zero and has undefined behaviour on overflow.

Why use ch – ‘0’ instead of ch – 48?

It states the intent, and the standard guarantees the digits are consecutive.

Why accumulate in long long?

It can hold values beyond the int range, so we can compare safely before converting back.

Should I use strtol instead?

On a hosted system, usually yes. It handles bases and reports errors. A custom parser makes sense on very small targets.

Why is INT_MIN special?

Its magnitude is one larger than INT_MAX, so negating it as an int would overflow. Our code compares in a wider type.

Does isspace need an unsigned char?

Yes. Passing a negative char value to the ctype functions is undefined behaviour.

Keep Learning with the Free C Programming Course

Safe input handling is a core embedded C programming skill. Continue to the next lecture or return to the course index.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →