Decimal, Hex, octal and binary number inter conversion

Discussion in 'C' started by shabbir, Oct 5, 2006.

  1. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    The article discusses about all the number formats viz Binary, Decimal, Octal, Hex and BCD (Binary coded decimal) and conversion from Decimal to Binary, Octal and Hex and also the reverse conversion.

    Binary



    A numbering system based on 2 in which 0 and 1 are the only available digits.

    Decimal



    decimal fraction: a proper fraction whose denominator is a power of 10

    Octal



    A numbering system that uses eight digits, 0 through 7. It is used as a shorthand system for representing binary characters that use six bits.

    Hexa Decimal



    A numbering system which uses a base of 16. The first ten digits are 0-9 and the next six are A-F.

    Binary to Decimal


    Code:
    void Bin2Dec()
    {
    	int bin,n,r,s=0,i;
    	printf("Enter a binary number\n");
    	scanf("%d",&bin);
    	n=bin;
    	for(i=0;n!=0;i++)
    	{
    		r=n%10;
    		s=s+r*(int)pow(2,i);
    		n=n/10;
    	}
    	printf("The equivalent number of %d is %d\n",bin,s);
    }
    

    Octal to Decimal


    Code:
    void Oct2Dec()
    {
    	int oct,n,r,s=0,i;
    	printf("Enter an octal number\n");
    	scanf("%d",&oct);
    	n=oct;
    	for(i=0;n!=0;i++)
    	{
    		r=n%10;
    		s=s+r*(int)pow(8,i);
    		n=n/10;
    	}
    	printf("The equivalent number of %d is %d\n",oct,s);
    }
    

    Hex to Decimal


    Code:
    void Hex2Dec()
    {
    	char hex[N];
    	int i,j,n[N],l;
    	long double dec=0;
    	printf("Enter the hexa decimal number and find it's decimal equivalent\n");
    	fflush(stdin);
    	gets(hex);
    	l=strlen(hex);
    	for(i=0;i<l;i++)
    	{
    		switch(hex[i])
    		{
    		case '0':
    			n[i]=hex[i]-48;     //Ascii code of 0 is 48  48-48=0//
    			break;
    		case '1':
    			n[i]=hex[i]-48;		//Ascii code of 1 is 49  49-48=1//
    			break;
    		case '2':
    			n[i]=hex[i]-48;		//Ascii code of 2 is 50  50-48=2//
    			break;
    		case '3':
    			n[i]=hex[i]-48;		//Ascii code of 3 is 51  51-48=3//
    			break;
    		case '4':
    			n[i]=hex[i]-48;		//Ascii code of 4 is 52  52-48=4//
    			break;
    		case '5':
    			n[i]=hex[i]-48;		//Ascii code of 5 is 53  53-48=5//
    			break;
    		case '6':
    			n[i]=hex[i]-48;		//Ascii code of 6 is 54  54-48=6//
    			break;
    		case '7':
    			n[i]=hex[i]-48;		//Ascii code of 7 is 55  55-48=7//
    			break;
    		case '8':
    			n[i]=hex[i]-48;		//Ascii code of 8 is 56  56-48=8//
    			break;
    		case '9':
    			n[i]=hex[i]-48;		//Ascii code of 9 is 57  57-48=9//
    			break;
    		case 'A':
    			n[i]=hex[i]-55;     //Ascii code of A is 65 65-55=10//
    			break;
    		case 'B':
    			n[i]=hex[i]-55;		//Ascii code of B is 65 66-55=11//
    			break;
    		case 'C':
    			n[i]=hex[i]-55;		//Ascii code of C is 65 67-55=12//
    			break;
    		case 'D':
    			n[i]=hex[i]-55;		//Ascii code of D is 65 68-55=13//
    			break;
    		case 'E':
    			n[i]=hex[i]-55;		//Ascii code of E is 65 68-55=14//
    			break;
    		case 'F':
    			n[i]=hex[i]-55;		//Ascii code of F is 65 69-55=15//
    			break;
    		}
    	}
    	for(i=0,j=l;i<l;i++,j--)
    		dec=dec+(n[j-1]*pow(16,i));
    	printf("The decimal equivalent is %lg \n",dec);
    }
    

    Decimal to Binary


    Code:
    void Dec2Bin()
    {
    	int n,bin[100],i,j;
    	printf("Enter A Number To Find It's Binary Equivalence\n");
    	scanf("%d",&n);
    	printf("The Binary Equivalent of %d is \t",n);
    	for(i=0;n!=0;i++)
    	{
    		bin[i]=n%2;
    		n=n/2;
    	}
    	for(j=i-1;j>=0;j--)
    	{
    		printf("%d",bin[j]);
    	}
    	printf("\n");
    }
    

    Decimal to Octal


    Code:
    void Dec2Oct()
    {
    	int n,r[10],i;
    	printf("Enter a number to find it's octal equivalent\n");
    	scanf("%d",&n);
    	printf("The octal equivalent of %d is ",n);
    	for(i=0;n!=0;i++)
    	{
    		r[i]=n%8;
    		n=n/8;
    	}
    	i--;
    	for(;i>=0;i--)
    		printf("%d",r[i]);
    	printf("\n");
    }
    

    Decimal to Hex


    Code:
    void Dec2Hex()
    {
    	int n,r[10],i;
    	printf("Enter a number to get its hexadecimal equivalent\n");
    	scanf("%d",&n);
    	for(i=0;n!=0;i++)
    	{
    		r[i]=n%16;
    		n=n/16;
    	}
    	i--;
    	for(;i>=0;i--)
    	{
    		if(r[i]==10)
    			printf("A");
    		else if(r[i]==11)
    			printf("B");
    		else if(r[i]==12)
    			printf("C");
    		else if(r[i]==13)
    			printf("D");
    		else if(r[i]==14)
    			printf("E");
    		else if(r[i]==15)
    			printf("F");
    		else
    			printf("%d",r[i]);
    	}
    	printf("\n");
    }
    

    Binary Coded Decimal (BCD)



    A coding system in which each decimal digit from 0 to 9 is represented by a 4-digit binary number.
     

    Attached Files:

    ehsano likes this.
  2. christina

    christina New Member

    Joined:
    Nov 15, 2006
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    I am still a student but a futuer web developer or
    Location:
    Angono, Rizal Philippines
    hi mr. shabbir. i saw your program conversion of decimal nos to binary which is our assignment, here in go4experts.com

    uhm...if you dont mind...will please put comments so i will be able to fully understand the program.thanks!
    Code:
    void Dec2Bin()
    {
        int n,bin[100],i,j;
        printf("Enter A Number To Find It's Binary Equivalence\n");
        scanf("%d",&n);
        printf("The Binary Equivalent of %d is \t",n);
        for(i=0;n!=0;i++)
        {
            bin[i]=n%2;
            n=n/2;
        }
        for(j=i-1;j>=0;j--)
        {
            printf("%d",bin[j]);
        }
        printf("\n");
    }
    thank you very much.i will be waiting for your reply. :)
     
    Last edited by a moderator: Nov 16, 2006
  3. christina

    christina New Member

    Joined:
    Nov 15, 2006
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    I am still a student but a futuer web developer or
    Location:
    Angono, Rizal Philippines
    if anyone can help me.pls someone put comments in mr. shabbir's program.thank you....
     
  4. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Where you want me to place the comment I dont understand
     
  5. ayat_Ace

    ayat_Ace New Member

    Joined:
    Jan 6, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    how can i write these programs with assemly languge 8088
    thank you
     
  6. ayat_Ace

    ayat_Ace New Member

    Joined:
    Jan 6, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    who can help me
     
  7. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Its just you who can help yourself. Apart from that if you are stuck somewhere we can.
     
  8. ayat_Ace

    ayat_Ace New Member

    Joined:
    Jan 6, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    thank you mr shabir any way but can help me where i can find the answer so that i can quickl reach it ! :)
     
  9. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    What answers you are talking about.
     
  10. ayat_Ace

    ayat_Ace New Member

    Joined:
    Jan 6, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    hi mr shabbir
    the answers i mean that you seems to me a very skillful experts so advise me to be good at assemly programming i mean that you know more than me about very powerful websites help me to improve my self in programming

    thanks alot
    could you send me your email please
    my email : ayat_ace@yahoo.com
     
  11. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    My email add is in the forum. Click on the contact us or also on my profile.
     
  12. rai_gandalf

    rai_gandalf New Member

    Joined:
    Nov 4, 2005
    Messages:
    46
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Final Year Comp Engg
    Location:
    Mumbai
    Home Page:
    http://mindpuncture.blogspot.com
    Hey Shabbir,
    Very useful thread, this one. The thing is one becomes so proficient in programming & concerned with advanced implementation issues, that one often forgets small snippets & nuggets of code such as this. ;) So, Thx a lot for it. :)

    Waise, I developed a Decimal Integer to Binary String or Hexa String Convertor. I have put the source code here .... ;)

    Ciao,
    Rajiv


    Code:
    /* Decimal Integer to Binary String or Hexa String Convertor */
    
    #include <stdio.h>
    #include <conio.h>
    #include <math.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define DEFAULTVAL 0
    
    char* dec_to_binstr(int,int=DEFAULTVAL);
    char* dec_to_hexstr(int,int=DEFAULTVAL);
    
    void main()
      {
      int choice;
      unsigned int decqty,numbits;
    
      do{
        clrscr();
        printf("1. DEC TO BIN\t2. DEC TO HEX\n3. EXIT");
        printf("\nEnter choice :  ");
        scanf("%d",&choice);
    
        if(choice==1 || choice==2)
          {
          printf("\n\n\nEnter the Decimal Quantity :  ");
          scanf("%d",&decqty);
          printf("\nEnter a specific Number of Bits/Hexa-Digits if you want the O/P to contain a specific number of bits");
          printf("\n(Enter '0' (or DEFAULTVAL) to leave blank so that program calculates required number of bits) :  ");
          scanf("%d",&numbits);
          }
    
        switch(choice)
          {
          default:
            printf("\n\nINVALID CHOICE!! Please Try Again!!");
          case 1:
            printf("\n\nBinary Equivalent is :  %s",dec_to_binstr(decqty,numbits));
            break;
          case 2:
            printf("\n\nHexadecimal Equivalent is :  %s",dec_to_hexstr(decqty,numbits));
            break;
          case 3:
            break;
          }
        getch();
        }while(choice!=3);
      }
    
    /* This Routine Converts a decimal Qty to binary Qty */
    char* dec_to_binstr(int decnum,int numbits)
      {
      int i,j,k;
      char *result;
      char *temp;
    
      printf("\n\n\nEntered in Routine :  dec_to_binstr()");
      printf("\ndecnum = %d\tnumbits = %d",decnum,numbits);
    
      // Calculating Number of bits required
      for(i=0;pow(2,i)<abs(decnum);i++);
    
      printf("\nNo. of bits reqd (i) = %d",i);
    
      // Checking Whether 'numbits' provided in Call is adequate
      if(numbits!=DEFAULTVAL && numbits<i)
        return "ERROR!! Incorrect 'numbits' Specification during Call!!";
    
      // Allocating Memory for 'temp' & 'result'
      else if(numbits==DEFAULTVAL)
        // No 'numbits' provided in call
        {
        temp=(char*)malloc((i+1)*sizeof(char));
        result=(char*)malloc((i+1)*sizeof(char));
        }
      else
        // Function call has provided the 'numbits'
        // Assuming that 'numbits' involves the 1 extra character slot required
        // in case of signed integers
        {
        temp=(char*)malloc((numbits+1)*sizeof(char));
        result=(char*)malloc((numbits+1)*sizeof(char));
        }
    
      // Performing Intermediate processing on 'temp'
      for(j=0;decnum>0;j++)
        {
        temp[j]=char('0'+decnum%2);
        decnum=decnum/2;
        }
    
      // Padding Any Bits Remaining if at all with Zeroes
      for(;j<numbits;j++)
        temp[j]='0';
      temp[j]='\0';
    
      // Forming the 'result' string by String Reversal
      k=0;
    
      if(numbits==DEFAULTVAL)
        j=i-1;
      else
        j=numbits-1;
    
      for(;j>=0;j--,k++)
        result[k]=temp[j];
      result[k]='\0';
    
      return result;
      }
    
    char* dec_to_hexstr(int decnum,int numbits)
      {
      int i,j,k;
      char *result;
      char *temp;
      int numtemp;
      
      printf("\n\n\nEntered in Routine :  dec_to_hexstr()!!");
      printf("\ndecnum = %d\tnumbits = %d",decnum,numbits);
    
      // Calculating Number of Hexa-digits required
      for(i=0;pow(16,i)<abs(decnum);i++);
    
      printf("\nNo. of Hexa-digits reqd (i) = %d",i);
    
      // Checking Whether 'numbits' provided in Call is adequate
      if(numbits!=DEFAULTVAL && numbits<i)
        return "ERROR!! Incorrect 'numbits' Specification during Call!!";
    
      // Allocating Memory for 'temp' & 'result'
      else if(numbits==DEFAULTVAL)
        // No 'numbits' provided in call
        {
        temp=(char*)malloc((i+1)*sizeof(char));
        result=(char*)malloc((i+1)*sizeof(char));
        }
      else
        // Function call has provided the 'numbits'
        // Assuming that 'numbits' involves the 1 extra character slot required
        // in case of signed integers
        {
        temp=(char*)malloc((numbits+1)*sizeof(char));
        result=(char*)malloc((numbits+1)*sizeof(char));
        }
    
      // Performing Intermediate processing on 'temp'
      for(j=0;decnum>0;j++)
        {
        numtemp=decnum%16;
        if(numtemp>=10)
          temp[j]=char('A'+(numtemp-10));
        else
          temp[j]=char('0'+numtemp);
        decnum=decnum/16;
        }
    
      // Padding Any Bits Remaining if at all with Zeroes
      for(;j<numbits;j++)
        temp[j]='0';
      temp[j]='\0';
    
      // Forming the 'result' string by String Reversal
      k=0;
    
      if(numbits==DEFAULTVAL)
        j=i-1;
      else
        j=numbits-1;
    
      for(;j>=0;j--,k++)
        result[k]=temp[j];
      result[k]='\0';
    
      return result;
      }
     
  13. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    My pleasure.

    Thats a good prog and when I will reach home will try running it.
     
  14. christina

    christina New Member

    Joined:
    Nov 15, 2006
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    I am still a student but a futuer web developer or
    Location:
    Angono, Rizal Philippines
    hi mr shabbir. i hope you receive my email to you. thank you very much to your program. i ask my other proffessor in school to help me, and he did, at first i dont understand but later on when i spend time (much time n_n' ) on i finally did it. all i can say that somehow, ur a genius sir.hee. coz i dont have the talent you possess. my talent is in drawing, i could be a future flash animator or a web developer.hee.ooopppss!!! why am i saying this.hee.sorry.
    But let me give you my WARM-BIG THANKS SIR!!!
    my prof gave me a grade of 91 for my effort and hardwork in hios subject.c=
    thanks a LOT!!
     
  15. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    christina, the pleasure is all mine but I would suggest one thing. Try to give something to the programming community from where you have got something and that may not necessarily be this forum.
     
  16. kunalkunal

    kunalkunal New Member

    Joined:
    Apr 1, 2007
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Need Help!

    Hey Shabbir,
    Can you help me something?
    I am BCA 1st sem. Student; I want a program in C language.

    Write a program to transform its input according to a specified transformation scheme. The transformation scheme will consist of two strings: a string of characters and then a string of replacement characters. The idea is that your program replaces every instance of the ith character in the initial string with the (i+3) character (of English alphabets) in the replacement string. When no substitution is defined for a character, the program just passes it through to the output unchanged. The program should inform the user of any errors in the transformation scheme. Your program should display the phrase before and after the substitutions have been made.
    Example:
    Original String: This is a C program.
    String after the transformation: Wklv lv d F Surjudp.


    Pls help
    Thanks in advance
     
  17. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    kunalkunal, 2 things I would suggest to get the best out of any forums / groups.

    1. Dont jump into others topic / article with your query.
    2. Dont ask us to complete your assignments but you can always ask us the best way of doing it.
     
  18. kunalkunal

    kunalkunal New Member

    Joined:
    Apr 1, 2007
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    you are right but i am new in c programming, then how can i done it ?
    so pls give me some tips
    thanks
     
  19. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  20. gbagnati

    gbagnati New Member

    Joined:
    May 11, 2007
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    One question to understand the conversion program from Decimal to Binary.
    How does the variable bin[100] work?
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice