What are Decimal to Binary in C- 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 →

Decimal to Binary in C

Lecture 26 of our free C programming course: write a decimal to binary program in C, see where the classic trick fails and use shift and mask for registers.

Welcome back to our free C programming course on EmbeddedPathashala. In this free C tutorial we write a decimal to binary program in C and, more importantly, we learn why it works. Binary is the native language of hardware. Every register you configure in embedded C programming, from a GPIO direction register to a timer control register, is a row of bits.

We study two ways to build the conversion. The first collects remainders with repeated division by 2 and is a classic exercise. The second uses shift and mask operations, the method real firmware uses. You will also meet the limits of the classic trick, including a textbook arithmetic slip worth knowing about.

What You Will Learn

  • How repeated division by 2 produces the binary digits of a number
  • What the MSB and the LSB are and how the remainders map to them
  • How to write a decimal to binary program in C with the digit-building trick
  • Why that trick breaks for larger values, shown with a measured result
  • How to print any value in binary with a shift-and-mask loop using fixed width
  • How the same idea reads single bits in hardware registers
  • How to verify a conversion by adding place values

Prerequisites

Before you start

  • You understand binary place values (1, 2, 4, 8, 16…) from the number systems chapter.
  • You know the % and / operators and can read a while loop.
  • You are comfortable with function parameters and return values from this chapter.

The Method: Repeated Division by 2

To convert a decimal number to binary by hand, divide it by 2, write down the remainder, divide the quotient by 2 again and continue until the quotient becomes 0. The remainders are the binary digits. The first remainder is the least significant bit (LSB), the rightmost digit. The last remainder is the most significant bit (MSB), the leftmost digit. Reading the remainders from last to first gives the binary number.

Why does this work? Dividing by 2 tells you whether the number is odd or even, and the remainder is the digit in the 1s place. The quotient then represents the rest of the number shifted one place to the right, so the next remainder is the digit in the 2s place, and so on.

Conversion loop in four steps
1

Divide

Compute quotient = n / 2 and remainder = n % 2.

2

Record

The remainder is the next binary digit, starting from the LSB.

3

Replace

Use the quotient as the new value of n.

4

Stop at zero

When n becomes 0 the last remainder recorded was the MSB.

Worked Example: Converting 29 to Binary

We ran a tiny program that prints each division step for 29, so the table below shows real values:

StepDivisionQuotientRemainderBit position
129 / 2141LSB
214 / 270
37 / 231
43 / 211
51 / 201MSB

The remainders in order of production are 1, 0, 1, 1, 1. Reading them from the last to the first gives 11101. Let us verify by adding place values: 1 x 16 + 1 x 8 + 1 x 4 + 0 x 2 + 1 x 1 = 16 + 8 + 4 + 0 + 1 = 29. The conversion is correct.

Binary 11101 and its place values

MSB side

bit 4 = 1 (weight 16) bit 3 = 1 (weight 8)

Middle

bit 2 = 1 (weight 4) bit 1 = 0 (weight 2)

LSB side

bit 0 = 1 (weight 1)
Watch out: A well-known textbook version of this example finishes with the sum 1*0 + 1*10 + 1*100 + 0*1000 + 1*10000 = 10111. That reads the remainders in the wrong order, and 10111 equals 23, not 29. The correct answer is 11101. Always check a conversion by adding the place values back up.

Decimal to Binary Program in C: The Digit-Building Trick

The first program builds a decimal number whose digits look like the binary number. Each remainder is multiplied by a power of 10 and added to the result. Because the first remainder is the LSB, it goes into the 1s place, the next into the 10s place and so on, so the digits end up in the right order without any reversing. The result is printed with %lu and looks like binary only because it contains just the digits 0 and 1.

Program bin1.c

#include <stdio.h>

/* classic trick: build a decimal number whose digits look like binary */
static unsigned long ep_dec_to_bin_digits(unsigned long n)
{
    unsigned long bin = 0, place = 1;

    while (n > 0) {
        bin += (n % 2) * place;
        n /= 2;
        place *= 10;
    }
    return bin;
}

int main(void)
{
    unsigned long values[] = { 29, 8, 255, 1023, 0 };
    for (size_t i = 0; i < sizeof values / sizeof values[0]; i++)
        printf("%lu -> %lu\n", values[i], ep_dec_to_bin_digits(values[i]));
    return 0;
}

Output:

29 -> 11101
8 -> 1000
255 -> 11111111
1023 -> 1111111111
0 -> 0
gcc -std=c11 -Wall -Wextra -o bin1 bin1.c
./bin1

The output for 29 is 11101, matching our hand conversion. Study how the three variables cooperate: n shrinks by half each pass, place grows by a factor of 10, and bin accumulates the answer.

Passn beforeremainderplacebin after
129111
2140101
371100101
43110001101
5111000011101

The Limit of the Digit-Building Trick

The trick stores binary digits inside a decimal number, so the number of binary digits is limited by how many decimal digits the variable can hold. A 64-bit unsigned long holds at most 20 decimal digits. We tried the value 2 to the power 20, which needs 21 binary digits:

Program binover.c

#include <stdio.h>
int main(void)
{
    unsigned long big = 1UL << 20;
    unsigned long bin = 0, place = 1, n = big;
    while (n) { bin += (n % 2) * place; n /= 2; place *= 10; }
    printf("2^20 as decimal-digit trick: %lu (expected 100000000000000000000, 21 digits)\n", bin);
    printf("ULONG_MAX is about 1.8e19 (20 digits)\n");
    return 0;
}

Output:

2^20 as decimal-digit trick: 7766279631452241920 (expected 100000000000000000000, 21 digits)
ULONG_MAX is about 1.8e19 (20 digits)

The printed number is nonsense, because the arithmetic wrapped around. On this 64-bit system the trick works only up to 20 binary digits. On many microcontrollers a long has only 32 bits and holds about 10 decimal digits, so the trick fails after just 10 binary digits, that is, for values above 1023. For real work you need a better method.

Watch out: The digit-building trick is a teaching exercise. Do not use it to display register values on a microcontroller. A 32-bit register has 32 bits, far more than the trick can hold.

A Better Decimal to Binary Program in C: Shift and Mask

A register is a fixed row of bits, so a firmware routine usually prints a fixed number of bits, including leading zeros. The standard technique examines one bit at a time. Shifting the value right by bit places moves the bit of interest into position 0, and AND with 1 isolates it. We start from the highest bit and move down, so the MSB prints first and no remainders need reversing.

Program bin2.c

#include <stdio.h>
#include <stdint.h>

static void ep_print_binary(uint32_t value, int width)
{
    for (int bit = width - 1; bit >= 0; bit--)
        putchar(((value >> bit) & 1u) ? '1' : '0');
    putchar('\n');
}

int main(void)
{
    ep_print_binary(29, 8);
    ep_print_binary(255, 8);
    ep_print_binary(0xA5, 8);
    ep_print_binary(1u << 31, 32);
    return 0;
}

Output:

00011101
11111111
10100101
10000000000000000000000000000000
Reading one bit with shift and mask
1

Choose a bit

Pick the position bit, counting from 0 at the LSB.

2

Shift right

value >> bit moves that bit into position 0.

3

Mask

& 1u clears every other bit and leaves 0 or 1.

4

Print

Output the character ‘0’ or ‘1’, then go to the next lower bit.

Notice the four calls. The value 29 prints as 00011101 in an 8-bit width: the same bits as 11101 with three leading zeros. The value 0xA5 prints as 10100101. The last call shows that the loop handles a full 32-bit width without any trouble.

Decimal to Binary in C: Comparing the Two Methods

AspectDigit-building trickShift and mask
IdeaRepeated division, remainders become digits of a decimal numberExamine each bit directly
Maximum bitsAbout 20 on a 64-bit long, about 10 on a 32-bit longAs many as the type has
Leading zerosLostControlled by the width argument
Division operatorUsed each pass, slow on small coresNot used, shifts are cheap
Typical useClassroom exerciseRegister dumps, debugging and protocol code

Real-World Uses in Embedded C Programming

A decimal to binary program in C is more than a classroom exercise, because binary thinking is the core skill of embedded C programming.

Binary thinking is the core skill of embedded C programming. To read the status of an input pin you test a single bit with shift and mask. To configure a peripheral you set and clear bits in a control register using OR and AND. A debugging helper like ep_print_binary() lets you dump a status register to a serial console and compare it bit by bit with the datasheet table. The same loop also helps when you check a communication frame, where each bit of a flag byte has a meaning.

OperationC expressionMeaning
Test bit n(reg >> n) & 1u1 if the bit is set
Set bit nreg |= (1u << n)Force the bit to 1
Clear bit nreg &= ~(1u << n)Force the bit to 0
Toggle bit nreg ^= (1u << n)Flip the bit

Negative Numbers and Signed Types

Any decimal to binary program in C must decide what to do with negative input. The division methods assume a non-negative number, because the loop ends when n is no longer greater than 0. For a negative signed value the loop would not run at all. Hardware stores negative integers in two’s complement form. To see those bits, cast the value to an unsigned type of the same size before printing: for example, the 32-bit value -1 becomes all ones, 0xFFFFFFFF. The shift-and-mask routine then shows exactly what the hardware holds.

Common Mistakes and Troubleshooting

MistakeSymptomFix
Reading remainders first to lastDigits come out reversedRead last to first, or build with place values
Using int for the digit-building resultOverflow after a few bitsUse shift and mask for real work
Shifting by the type width or moreUndefined behaviourKeep bit below the number of bits in the type
Shifting a signed value into the sign bitUnexpected resultUse unsigned types, such as 1u, for masks
Forgetting leading zerosRegister dump is hard to comparePrint a fixed width

Best Practices, Performance and Security

Best practices

  • Use fixed-width types such as uint32_t from <stdint.h> for register values.
  • Write masks with the u suffix, as in 1u << n, to avoid signed shift problems.
  • Verify conversions by adding place values back to the decimal number.
  • Wrap bit helpers in small named functions so the intent stays clear.

For performance, shifts and masks are single instructions on most cores, while division may take many cycles on small processors without a hardware divider. For security, never shift by an amount that comes from untrusted data without checking that it is below the width of the type, because shifting by too many places is undefined behaviour.

Summary and Key Takeaways

Remember

  • Divide by 2 repeatedly, collect the remainders, and read them from last to first.
  • The first remainder is the LSB and the last remainder is the MSB.
  • 29 in decimal is 11101 in binary, because 16 + 8 + 4 + 1 = 29.
  • The digit-building trick is limited by the digits a variable can hold.
  • Shift and mask gives a reliable, fixed-width decimal to binary program in C for real firmware.

Conclusion

You now know two ways to write a decimal to binary program in C, you have seen where the classic trick fails, and you can use shift and mask to inspect any register. This closes the programs section of the functions chapter in our free C programming course. The final file in this batch is a practice lab: a quiz, output puzzles, coding challenges and interview questions on everything from library functions to number conversion.

Frequently Asked Questions

How do you convert decimal to binary in C?

Divide the number by 2 repeatedly and record the remainders, then read them from last to first. In firmware you usually shift and mask each bit instead.

What is the MSB and the LSB in a binary number?

The MSB is the most significant bit, the leftmost digit with the largest weight. The LSB is the least significant bit, the rightmost digit with weight 1.

What is 29 in binary?

29 is 11101 in binary, because 16 + 8 + 4 + 1 = 29.

Why does the digit-building trick fail for large numbers?

It stores binary digits in a decimal number, so the result needs one decimal digit per bit and overflows a variable after about 20 digits on 64-bit long and about 10 digits on 32-bit long.

How do I print a number in binary with leading zeros?

Loop from the highest bit to bit 0 and print (value >> bit) & 1u for each position, using a fixed width.

How do I see the bits of a negative number?

Cast it to an unsigned type of the same width, then shift and mask. The result shows the two’s complement pattern that the hardware stores.

Is this decimal to binary lesson part of a free embedded C course?

Yes. It belongs to the free C programming course from EmbeddedPathashala, written for learners of C programming for embedded systems.

Keep Going With the Free Embedded C Course

Next is the practice lab: a quiz, output puzzles, coding challenges and interview questions on this whole section.

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