Is there a printf() converter to print in binary format?

In this tutorial, we will learn about the binary format and if there is a converter for them in C programming language.
Submitted by Shubh Pachori, on July 10, 2022

Binary means something made of two things or parts. A binary number is a number expressed in the base-2 numeric system or binary numeric system. It is a method of mathematical expression which uses only two symbols i.e; 0 and 1. It is a positional notation with a radix of 2. Each digit in the binary numeric system is referred to as a bit or binary digit. It is the smallest unit of data in the computing system. Computer represents numbers using binary code in the form of digital 0 and 1 inside the CPU and RAM. These generated digital numbers that are 0 and 1 are electrical signals that are either on or off the inside the CPU or RAM.

For example, the Binary digits of decimal values: 2 is 10,3 is 11,4 is 100 etc.

In C programming language there isn't any printf() function converter to print in binary format. There is also not a binary conversion specifier in glibc (GNU Project's implementation of the C standard library) normally. But if we want to do so we have to create custom conversion types to print the binary format by using existing format specifiers and datatypes.

C program to convert a number to the binary format

#include <stdio.h>

int main()
{
    // Two int variable and a array to 
    // store the binary format
    int a[10], n, i;

    // Input  an integer number
    printf("Enter the Number: "); 
    scanf("%d", &n);

    // Loop to calculate and store the binary format
    for (i = 0; n > 0; i++) {
        a[i] = n % 2;
        n = n / 2;
    }

    printf("\nBinary Format:");

    // Loop to print the binary format of given number
    for (i = i - 1; i >= 0; i--) 
    {
        printf("%d", a[i]);
    }

    return 0;
}

Output:

Enter the Number: 128

Binary Format:10000000

Here in the given method, we have used custom codes to convert a numeric value to the binary format.




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.