🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Free C Programming Course · Strings · Lecture 39
C Integer to String Conversion
Convert integers to text in binary, octal, decimal or hex with a bounds-checked function. Practical embedded C programming from our free C tutorial.
Debug prints, LCD screens, log files and protocol frames all need numbers as text. The standard library gives you printf and snprintf, but on small microcontrollers you often want a lightweight routine of your own, and you often need bases that printf does not offer, such as binary. In this lecture of our free C programming course you will write an integer to string conversion in C that supports bases 2 to 16, handles zero and negative numbers correctly, and refuses to overflow its buffer. It is a staple of embedded C programming and a classic interview topic in any free embedded C course.
What You Will Learn
- How repeated division produces digits in any base
- Why digits come out in reverse order and how to fix it
- How to use a digit lookup string instead of character arithmetic
- How to handle zero and negative numbers, including the most negative value
- How to make the function refuse a buffer that is too small
Prerequisites
You should understand number systems (binary, octal, hexadecimal), the NUL terminator and fixed-width types from <stdint.h>. These appear in earlier lectures of this free C programming course.
Repeated Division: The Core Idea
To write a number in base b, divide it by b repeatedly. Each remainder is the next digit, starting from the least significant one. For 45 in base 2:
45 in base 2: remainders appear in reverse
The remainders come out last digit first, so the text has to be reversed. There are two simple ways: build the digits in a temporary array and copy them backwards, or fill the output from the end. We use the temporary array because it makes the length known before we touch the caller’s buffer.
A Digit Lookup String
Many examples convert a remainder with branches: if it is above 9 add ‘A’ minus 10, otherwise add ‘0’. A lookup string is cleaner. With "0123456789ABCDEF" the remainder is directly the index, so one expression covers every base up to 16.
| Remainder | 0-9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|
| Digit char | ‘0’ to ‘9’ | A | B | C | D | E | F |
Three Edge Cases That Break Naive Code
- Zero. A loop written as
while (v > 0)never runs for 0, leaving an empty string. Ado/whileloop always emits at least one digit. - Negative numbers. Division and remainder of negative values give negative remainders in C. Convert the magnitude as unsigned and add the minus sign yourself.
- The most negative number. Negating INT32_MIN as a signed value overflows. The expression
0u - (uint32_t)vcomputes the magnitude safely in unsigned arithmetic.
Warning: check the buffer size first. A 32-bit value in base 2 needs 32 digits plus the terminator, and a sign needs one more byte. If your function does not verify the capacity, a short buffer becomes a stack overflow.
The Complete Program
#include <stdio.h>
#include <stdint.h>
#include <string.h>
/* writes value in given base (2..16). returns length, or -1 if buffer too small */
int uint_to_str(uint32_t v, char *buf, size_t cap, unsigned base)
{
static const char digits[] = "0123456789ABCDEF";
char tmp[33];
size_t n = 0;
if (base < 2 || base > 16 || cap == 0)
return -1;
do {
tmp[n++] = digits[v % base];
v /= base;
} while (v != 0);
if (n + 1 > cap)
return -1;
for (size_t i = 0; i < n; i++)
buf[i] = tmp[n - 1 - i];
buf[n] = '\0';
return (int)n;
}
int int_to_str(int32_t v, char *buf, size_t cap)
{
if (v >= 0)
return uint_to_str((uint32_t)v, buf, cap, 10);
if (cap < 2)
return -1;
buf[0] = '-';
uint32_t mag = 0u - (uint32_t)v; /* safe even for INT32_MIN */
int n = uint_to_str(mag, buf + 1, cap - 1, 10);
return n < 0 ? -1 : n + 1;
}
int main(void)
{
char b[40];
unsigned bases[] = {16, 10, 8, 2};
for (int i = 0; i < 4; i++) {
uint_to_str(45, b, sizeof b, bases[i]);
printf("45 in base %-2u = %s\n", bases[i], b);
}
uint_to_str(0, b, sizeof b, 2);
printf("0 in base 2 = %s\n", b);
int_to_str(-45, b, sizeof b);
printf("-45 = %s\n", b);
int_to_str(INT32_MIN, b, sizeof b);
printf("INT32_MIN = %s\n", b);
uint_to_str(0xDEADBEEF, b, sizeof b, 16);
printf("0xDEADBEEF = %s\n", b);
char tiny[4];
int r = uint_to_str(12345, tiny, sizeof tiny, 10);
printf("12345 into 4 bytes -> %d (rejected)\n", r);
return 0;
}
Build and Run
$ gcc -std=c11 -Wall -Wextra -o itoa itoa.c
$ ./itoa
Expected Output
45 in base 16 = 2D
45 in base 10 = 45
45 in base 8 = 55
45 in base 2 = 101101
0 in base 2 = 0
-45 = -45
INT32_MIN = -2147483648
0xDEADBEEF = DEADBEEF
12345 into 4 bytes -> -1 (rejected)
Walking Through the Code
uint_to_str
The temporary array has 33 slots: 32 for a base-2 value of 32 bits plus one spare. The do/while loop guarantees at least one digit, so zero prints as “0”. After the loop we know the digit count n, so we can check n + 1 > cap before touching the caller’s memory. If there is not enough room, nothing is written at all.
int_to_str
Non-negative values go straight to the unsigned routine. For negative values we write the minus sign, compute the magnitude in unsigned arithmetic, and convert it into the rest of the buffer. The final return value counts the sign as well.
Comparing the Options
| Method | Bases | Bounds check | Code size |
|---|---|---|---|
| Own function (this lecture) | 2 to 16 | yes | small |
snprintf("%d") | 10 only | yes | larger |
snprintf("%x"), %o | 16 and 8 | yes | larger |
Non-standard itoa | 2 to 36 | no | varies, not portable |
Note that itoa is not part of standard C. Code that depends on it may not compile on another toolchain, which is one more reason to own a small, tested routine.
Performance Considerations
- Division is slow on cores without a hardware divider, such as Cortex-M0. For fixed bases you can use shifts: base 16 is
v & 0xFandv >> 4. - Avoiding
printfcan save several kilobytes of flash on small parts. - Using a lookup string avoids a branch per digit.
Real-World Use Cases
- Hex dumps of registers and memory in a debug console.
- Binary display of status flags and GPIO states.
- Numeric fields inside text protocols such as AT commands or NMEA sentences.
- Log timestamps on devices without a full C library.
Common Mistakes
- Using while (v > 0) and printing nothing for zero.
- Forgetting to reverse the digits.
- Forgetting the NUL terminator, or allocating a buffer one byte too small.
- Negating INT_MIN as a signed int.
- Returning a pointer to a local array. The array disappears when the function returns; always use a caller-supplied buffer.
- Not rejecting a base of 0, 1 or above 16. Base 1 causes an endless loop.
Best Practices
- Check the buffer capacity before writing anything.
- Take the buffer size as an argument; never assume it.
- Convert negative numbers through an unsigned magnitude.
- Test with 0, 1, a base-boundary value, a negative, INT32_MIN and UINT32_MAX.
- Compare against
snprintfoutput in a unit test to prove correctness.
Suggested Images
| Image idea | Suggested ALT text |
|---|---|
| Repeated division of 45 by 2 with remainders | integer to string conversion in C using repeated division, free C programming course |
| Table comparing own function, snprintf and itoa | itoa alternative in embedded C programming, free C tutorial |
| Hex dump on a serial console | hex and binary output in embedded C, free embedded C course |
Summary and Key Takeaways
- Remainders from repeated division are digits, produced last digit first.
- A lookup string maps a remainder to its character for any base up to 16.
- Use do/while so zero works, and convert negatives through an unsigned magnitude.
- Always check capacity before writing into the caller’s buffer.
itoais not standard; write and test your own.
Conclusion
You have written a small, safe integer to string converter that supports any base from 2 to 16. It handles the awkward cases that trip up most first attempts: zero, negative values and the smallest signed number. In the next lecture of this free C programming course we tackle a harder cousin: printing floating point numbers on a system with no floating point printf.
Frequently Asked Questions
Why do digits come out reversed?
Division by the base gives the least significant digit first, so the text must be reversed before use.
Is itoa a standard C function?
No. Many compilers provide it, but it is not in the C standard and behaves differently across toolchains.
How big should my buffer be?
For 32-bit values: 33 bytes for base 2, plus one more for a minus sign. Base 10 needs 11 bytes including sign and terminator.
How do I handle INT_MIN?
Convert the magnitude using unsigned arithmetic, for example 0u minus the value cast to unsigned.
Can I avoid division on a small MCU?
For bases 2, 8 and 16 use masks and shifts. For base 10 some compilers optimise division by a constant into multiplication.
Why not just use snprintf?
You can on most systems. A custom routine is smaller, supports binary and avoids the larger printf code on tiny devices.
Keep Learning with the Free C Programming Course
Numbers to text is a daily task in firmware. Continue to the next lecture in this free embedded C course.

2 Comments