Thursday, November 22, 2018

C code review takes integer and shows its binary form

This C code shows how to convert integer input into binary and shows it to user. And code is helpful in boolearn algebra.

code:

//Tested Ok on Code::Blocks IDE 17.12 & Cygwin + GCC tools.
/*The program takes an integer as input and shows its binary form.*/

#include <stdio.h>

void showbits(int n);

void main()
{
    int n;
    char ch;
    while(1)
    {
        //clrscr();
        printf("\nEnter an integer to see its Binary Equivalent: ");
        scanf("%d",&n);
        showbits(n);

        printf("\ncontinue ? x=to exit \t Any letter to continue\n");

        while((ch=getchar())== '\n');

        if(ch=='x')
            break;
    }
}/*End of main()*/

void showbits(int n)
{
    int i,bit,mask,count=0;
    printf("    ");
    for(i=15; i>=0; i--)
    {
        mask=1<<i;

        bit=n & mask;

        if(bit==mask)
            printf("1");
        else
            printf("0");
        count++;
        if(count%4==0)
            printf("  ");
    }
}/*End of showbits()*/

//end of program

To see such C code reviews refer blog archieve at right side or click CCode lable for till posted posts list.

...till next post, bye-bye and take care.

No comments:

Post a Comment