Cover Image for Decimal to Binary in C
185 views

Decimal to Binary in C

To convert a decimal number to binary in C, you can use a loop that repeatedly divides the decimal number by 2 and keeps track of the remainders. The remainders, read in reverse order, form the binary representation of the decimal number. Here’s a C program to perform this conversion:

C
#include <stdio.h>

int main() {
    int decimalNum;
    printf("Enter a decimal number: ");
    scanf("%d", &decimalNum);

    if (decimalNum < 0) {
        printf("Negative numbers are not supported for this example.\n");
        return 1;
    }

    int binary[32]; // Array to store binary digits (32 bits for an int)
    int index = 0;

    while (decimalNum > 0) {
        binary[index] = decimalNum % 2;
        decimalNum /= 2;
        index++;
    }

    if (index == 0) {
        // The input was 0
        printf("Binary: 0\n");
    } else {
        printf("Binary: ");
        for (int i = index - 1; i >= 0; i--) {
            printf("%d", binary[i]);
        }
        printf("\n");
    }

    return 0;
}

In this program:

  • We take a decimal number as input from the user.
  • We check if the input number is negative, and if it is, we print an error message and exit the program.
  • We use an array binary to store the binary digits of the number. We assume a maximum of 32 bits for an integer, so the array size is set to 32.
  • We use a while loop to repeatedly divide the decimal number by 2 and store the remainder (0 or 1) in the binary array. This process continues until the decimal number becomes 0.
  • Finally, we print the binary representation by iterating through the binary array in reverse order.

Compile and run the program, and it will convert the entered decimal number into its binary representation.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS