What is Recursive Number Base Conversion- Learn C Programming Online Free

🚀 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 →

C Programming for Embedded Systems | Chapter 6 Functions

Recursive Number Base Conversion

Print any number in binary, octal or hexadecimal with a three-line recursive function, a core skill in C programming for embedded systems.

6
Chapter: Functions
47
Lecture number
C99
Tested with GCC

Every register dump, memory address and bit mask you meet in C programming for embedded systems is written in binary, octal or hexadecimal rather than decimal. In this lecture of our free embedded C course you will write a compact recursive function that prints any number in any base from 2 to 36, then wrap it in a menu-driven program with proper input checking. Along the way you will see why recursion is a natural fit for this particular problem, where the hidden dangers are, and how to make the converter safe enough to trust on real hardware.

The remarkable thing is how little code is needed. The whole converter is three lines, and understanding why those three lines work, in that order, teaches more about the call stack than a page of theory.

What You Will Learn About C Programming for Embedded Systems Here

  • The repeated division and remainder method for converting a decimal value to any base.
  • Why remainders appear in the wrong order and how recursion fixes that during unwinding.
  • How a digit lookup string replaces branching and extends the converter up to base 36.
  • How to write both a printing version and a version that fills a caller-owned buffer.
  • Why bases 0 and 1 must be rejected, and what happens if you forget.
  • How to build a menu loop with input validation, and how to verify the converter against printf.

Prerequisites

You need working knowledge of recursion with a base case, the remainder and division operators, switch and loops, and basic scanf and printf usage. The previous lecture on peeling digits with % 10 and / 10 is the direct warm-up, because converting to base b is the same idea with b in place of ten. No hardware is needed to follow this part of C programming for embedded systems; a PC compiler is enough.

Positional Notation in Thirty Seconds

In any positional system the value of a digit string is the sum of each digit multiplied by the base raised to the digit’s position, counting from zero at the right. The decimal number 2026 means 2 thousands, 0 hundreds, 2 tens and 6 ones. Binary uses powers of two, octal powers of eight and hexadecimal powers of sixteen.

SystemBaseDigits usedBits per digitTypical embedded use
Binary20 11bit masks, flag fields, GPIO patterns
Octal80 to 73file permission modes on Linux targets
Decimal100 to 9not a whole number of bitshuman-facing readouts
Hexadecimal160 to 9, A to F4addresses, register values, byte dumps

Hexadecimal dominates firmware work because four bits make exactly one digit, so a byte is always two digits and a 32-bit register is always eight. Reading a register in binary would be tedious and in decimal would hide the bit boundaries entirely.

The Division and Remainder Method

To convert a value to base b, divide it by b repeatedly. Each remainder is one digit of the answer, produced starting from the least significant digit. Stop when the quotient reaches zero. The catch is the order: the last remainder you compute is the first digit you must write.

StepValueDivide by 2Remainder (digit)
137181
21890
3941
4420
5210
6101

Reading the remainders from the bottom up gives 100101, the binary form of 37. A loop-based solution must store the digits and then reverse them. Recursion gets the reversal for free.

Why Recursion Reverses the Order for Free

Each call pauses while its deeper call runs, and the paused calls resume in the opposite order from which they started. If the function first recurses on the quotient and only then prints its own remainder, then the deepest call, which holds the most significant digit, prints first. The earlier calls print afterwards, moving toward the least significant digit. The stack does the reversing work.

Winding down and unwinding for print_in_base(37, 2)
FramenOn the way downOn the way back up
137calls with 18prints 37 % 2 = 1 (last)
218calls with 9prints 18 % 2 = 0
39calls with 4prints 9 % 2 = 1
44calls with 2prints 4 % 2 = 0
52calls with 1prints 2 % 2 = 0
611 is below the base, no deeper callprints 1 % 2 = 1 (first)
Order in which characters reach the screen
frame 6 prints1then frame 50then frame 40then frame 31then frame 20then frame 11

The Converter in Three Lines

The base case is folded into a single comparison. If the number is at least as large as the base, there are more digits to the left, so recurse on the quotient. Either way, print the digit for this level. A short lookup string replaces the clumsy branch that adds ‘A’ for remainders of ten or more, and it automatically supports digits up to Z.

static const char digit_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

static void print_in_base(unsigned long n, unsigned base)
{
    if (n >= base)
        print_in_base(n / base, base);
    putchar(digit_chars[n % base]);
}

Notice how zero is handled without special code: when n is 0, the comparison fails, no recursion happens, and the single digit 0 is printed. Choose lowercase letters in the lookup string if your tools expect lowercase hexadecimal.

Never Trust the Base: A Checked Wrapper

The three-line function has a trap. A base of 0 divides by zero. A base of 1 is worse: n / 1 equals n, so the number never shrinks, the comparison n >= 1 stays true, and the function calls itself until the stack is exhausted. On a desktop that is a crash, on a microcontroller it can silently corrupt memory next to the stack. Any base above 36 would read past the end of the lookup string. The fix is one guard in a public wrapper, leaving the recursive worker clean.

static int print_checked(unsigned long n, unsigned base)
{
    if (base < 2 || base > 36)
        return -1;
    print_in_base(n, base);
    return 0;
}

Writing into a Buffer Instead of the Screen

Printing straight from the converter is convenient for a demo, but real firmware often needs the text in memory first, perhaps to send over a UART in one burst or to place on a display. The buffer version uses the same recursion, but it returns the next free slot so each level knows where to write, and it keeps the string terminated after every digit.

static char *write_in_base(unsigned long n, unsigned base, char *dst)
{
    if (n >= base)
        dst = write_in_base(n / base, base, dst);
    *dst++ = digit_chars[n % base];
    *dst = '\0';
    return dst;
}

Size the buffer from the worst case. A 64-bit value in base 2 needs 64 digits plus the terminating null byte, so 65 bytes, while base 16 needs only 17. The recursion depth equals the digit count, so base 2 is also the deepest case: 32 frames for a 32-bit value and 64 for a 64-bit value.

C Programming for Embedded Systems: Complete Converter with Output

The listing prints a table for seven values in three bases, compares octal and hexadecimal results against the standard library for every value from 0 to 100000, shows base 36, and demonstrates that bad bases are refused.

#include <stdio.h>
#include <string.h>

static const char digit_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

/* prints n in the given base (2..36); recursion emits the most significant digit first */
static void print_in_base(unsigned long n, unsigned base)
{
    if (n >= base)
        print_in_base(n / base, base);
    putchar(digit_chars[n % base]);
}

/* public entry point: refuses bases that would divide by zero or never shrink n */
static int print_checked(unsigned long n, unsigned base)
{
    if (base < 2 || base > 36)
        return -1;
    print_in_base(n, base);
    return 0;
}

/* same idea, but writes into a caller supplied buffer and returns the next free slot */
static char *write_in_base(unsigned long n, unsigned base, char *dst)
{
    if (n >= base)
        dst = write_in_base(n / base, base, dst);
    *dst++ = digit_chars[n % base];
    *dst = '\0';
    return dst;
}

int main(void)
{
    static const unsigned long values[] = {0UL, 10UL, 37UL, 255UL, 1000UL, 2026UL, 65535UL};
    static const unsigned bases[] = {2, 8, 16};
    static const unsigned bad_bases[] = {0, 1, 37};
    size_t i, j;
    unsigned long n;
    int mismatches = 0;
    char buf[80], ref[80];

    printf("%7s %18s %8s %6s\n", "value", "binary", "octal", "hex");
    for (i = 0; i < sizeof values / sizeof values[0]; i++) {
        printf("%7lu ", values[i]);
        for (j = 0; j < 3; j++) {
            write_in_base(values[i], bases[j], buf);
            printf("%*s ", j == 0 ? 18 : (j == 1 ? 8 : 6), buf);
        }
        putchar('\n');
    }

    for (n = 0; n <= 100000UL; n++) {
        write_in_base(n, 8, buf);
        sprintf(ref, "%lo", n);
        if (strcmp(buf, ref) != 0)
            mismatches++;
        write_in_base(n, 16, buf);
        sprintf(ref, "%lX", n);
        if (strcmp(buf, ref) != 0)
            mismatches++;
    }
    printf("\noctal and hex compared with printf for 0..100000, mismatches: %d\n", mismatches);

    printf("base 36 of 123456789: ");
    print_checked(123456789UL, 36);
    putchar('\n');

    for (i = 0; i < sizeof bad_bases / sizeof bad_bases[0]; i++)
        printf("base %u rejected with code %d\n", bad_bases[i], print_checked(99UL, bad_bases[i]));
    return 0;
}
gcc -std=c99 -Wall -Wextra -pedantic -o base base.c
./base

Output from a real run:

  value             binary    octal    hex
      0                  0        0      0 
     10               1010       12      A 
     37             100101       45     25 
    255           11111111      377     FF 
   1000         1111101000     1750    3E8 
   2026        11111101010     3752    7EA 
  65535   1111111111111111   177777   FFFF 

octal and hex compared with printf for 0..100000, mismatches: 0
base 36 of 123456789: 21I3V9
base 0 rejected with code -1
base 1 rejected with code -1
base 37 rejected with code -1

Check a few rows by hand. 255 is FF in hexadecimal, eight ones in binary and 377 in octal, which matches the grouping rule of one hex digit per four bits and one octal digit per three. The zero mismatches line confirms the recursive converter agrees with printf for 200002 checks. The last three lines show that bases 0, 1 and 37 all return -1 without ever starting the recursion.

A Menu-Driven Front End with Validation

Students often build a menu around the converter. The version below offers binary, octal and hexadecimal, repeats until the user quits, rejects invalid options with a message, and checks the return value of scanf so that a closed input stream or a letter typed instead of a number cannot cause an endless loop.

#include <stdio.h>

static const char digit_chars[] = "0123456789ABCDEF";

static void emit(unsigned long n, unsigned base)
{
    if (n >= base)
        emit(n / base, base);
    putchar(digit_chars[n % base]);
}

int main(void)
{
    int choice;
    unsigned long value;
    unsigned base = 0;

    for (;;) {
        puts("1 binary  2 octal  3 hexadecimal  4 quit");
        printf("choice> ");
        if (scanf("%d", &choice) != 1) {
            puts("input ended");
            break;
        }
        if (choice == 4) {
            puts("bye");
            break;
        }
        switch (choice) {
        case 1: base = 2;  break;
        case 2: base = 8;  break;
        case 3: base = 16; break;
        default:
            puts("not a valid option, try again");
            continue;
        }
        printf("decimal value> ");
        if (scanf("%lu", &value) != 1) {
            puts("not a number");
            break;
        }
        printf("result: ");
        emit(value, base);
        putchar('\n');
    }
    return 0;
}

I ran it with piped input that chooses binary for 10, hexadecimal for 255, an invalid option 9, octal for 64 and finally quit:

1 binary  2 octal  3 hexadecimal  4 quit
choice> decimal value> result: 1010
1 binary  2 octal  3 hexadecimal  4 quit
choice> decimal value> result: FF
1 binary  2 octal  3 hexadecimal  4 quit
choice> not a valid option, try again
1 binary  2 octal  3 hexadecimal  4 quit
choice> decimal value> result: 100
1 binary  2 octal  3 hexadecimal  4 quit
choice> bye

Because the input was piped, the prompts appear back to back on one line. In a terminal each answer you type moves to a new line. The invalid option 9 triggers the message and the continue statement jumps straight back to the menu, so the unset base is never used. The loop ends with return instead of calling exit in the middle of the program, which keeps cleanup in one place and makes the function easier to test.

Real-World Uses in Embedded Systems

  • Debug output: minimal firmware often avoids the full printf family because it adds noticeable code size, so a small hex printer for UART logs is a standard utility.
  • Register inspection: showing a peripheral status register in binary reveals which flags are set at a glance.
  • Addresses and identifiers: memory addresses, device IDs and MAC address bytes are naturally hexadecimal.
  • Permission and mode values: embedded Linux targets display file modes in octal.
  • Compact encodings: base 32 or base 36 strings make short, readable device codes.

Common Mistakes in C Programming for Embedded Systems Conversions

SymptomLikely causeFix
Digits appear reversedDigit printed before the recursive callRecurse first, print the remainder afterwards
Nothing printed for zeroLoop or base case that stops at n == 0 without printingUse n >= base as the condition so a lone digit always prints
Crash or reset for base 1Quotient never shrinks, infinite recursionReject bases below 2 in a wrapper
Garbage characters for large digitsBase above the lookup string lengthLimit the base to 36 or extend the table
Negative numbers print oddlySigned remainder or sign confusionConvert as unsigned, or print a minus sign and negate safely first
Infinite menu loop on bad inputReturn value of scanf ignoredTest that scanf returned 1 before using the value

Best Practices, Performance and Security

Good C programming for embedded systems favours small, predictable routines whose worst case you can state in advance.

  • Keep the recursive worker minimal and put validation in a public wrapper.
  • Use unsigned arguments for bit patterns so shifts and divisions behave predictably.
  • Prefer a lookup string to a branch; it is shorter, faster to read and easier to extend.
  • Bound the depth. For base 2 the depth equals the bit width, which is acceptable here, but remember coding standards that forbid recursion and keep a loop-with-buffer alternative ready.
  • Performance: each digit costs one division and one remainder. For powers of two such as 2, 8 and 16 you can replace them with shifts and masks, which is much cheaper on cores without a hardware divider.
  • Security: the buffer version writes through a pointer without knowing the capacity. Always size buffers for the worst case, or add a capacity parameter as in the Roman numeral lecture.

Key Takeaways and Conclusion

Key takeaways

  • Converting to base b means repeated division by b, with the remainders as digits from least to most significant.
  • Recursing before printing makes the call stack reverse the digits so they appear in the correct order.
  • A lookup string of digit characters supports every base up to 36 with no branching.
  • Bases 0 and 1 must be rejected before recursion; base 1 would otherwise recurse forever.
  • Always check the return value of scanf and size output buffers for the widest value in base 2.
  • Validation wrappers and bounded buffers are everyday habits in C programming for embedded systems.

You now own a converter small enough to memorise, verified against the standard library, protected against bad input and adapted for both the screen and a buffer. More importantly, you have seen the order of statements around a recursive call decide the order of output, and you have practised the discipline that C programming for embedded systems demands: validate inputs, bound memory, and test against a trusted reference. The final lecture of this group collects everything from these pages into a quiz and a set of interview questions so you can test your own understanding.

Frequently Asked Questions: Base Conversion in C

Why does recursion print the digits in the correct order?

Remainders are produced from the least significant digit upward. Recursing on the quotient first means the deepest call, holding the most significant digit, prints first as the calls unwind.

What happens if the base is 1?

Dividing by 1 never shrinks the number, so the function calls itself until the stack is exhausted. Always validate that the base is at least 2 before recursing.

What is the largest base this converter supports?

Base 36, because the digit lookup string holds the ten digits and twenty-six letters. A larger base would read past the end of the string.

How do I convert negative numbers?

Convert as an unsigned value to see the two’s complement bit pattern, or print a minus sign and then convert the magnitude, taking care with the most negative value of the type.

How large a buffer does the buffer version need?

For a 64-bit value in base 2 you need 64 digits plus a terminating null, so 65 bytes. Base 16 needs only 17 bytes.

Can I avoid division when the base is a power of two?

Yes. For base 2, 8 or 16 you can use shifts by 1, 3 or 4 bits and masks, which is much cheaper on cores without a hardware divider.

Test What You Learned

Finish this group with the quiz and interview lecture to check your understanding of C programming for embedded systems.

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

1 Comment

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 →