
- Learn C By Examples Time
- Learn C by Examples - Home
- C Examples - Simple Programs
- C Examples - Loops/Iterations
- C Examples - Patterns
- C Examples - Arrays
- C Examples - Strings
- C Examples - Mathematics
- C Examples - Linked List
- C Programming Useful Resources
- Learn C By Examples - Quick Guide
- Learn C By Examples - Resources
- Learn C By Examples - Discussion
Octal To Binary program in C
Implementation
Implementation of this algorithm is given below −
#include <stdio.h> int string_length(char s[]) { int i=0; while(s[i]!='\0') i++; return i; } void string_reverse(char s[]) { char *t; for(t=s+string_length(s)-1;s<t;++s,--t) { char temp=*s; *s=*t; *t=temp; } } int binary2decimal(char n[]) { int i,decimal,mul=0; for(decimal=0,i=string_length(n)-1;i>=0;--i,++mul) decimal+=(n[i]-48)*(1<<mul); return decimal; } void printHexDigit(int d) { if(d<10) printf("%d",d); else if(d==10) printf("A"); else if(d==11) printf("B"); else if(d==12) printf("C"); else if(d==13) printf("D"); else if(d==14) printf("E"); else if(d==15) printf("F"); } int main() { char n[10],bits[100],temp[5]; int i,j,d; printf("Enter a octal number : "); scanf("%s",n); string_reverse(n); for(i=j=0;n[i]!='\0';++i) for(d=n[i]-48;d!=0;d/=2) bits[j++]=d%2+48; bits[j]='\0'; string_reverse(bits); for(i=j=0;i<string_length(bits)%4;++i,++j) temp[j]=n[i]; temp[j]='\0'; printf("Hexa equivalent is : "); d=binary2decimal(temp); if(d!=0) printHexDigit(d); while(bits[i]!='\0') { for(j=0;j<4;++i,++j) temp[j]=bits[i]; temp[j]='\0'; d=binary2decimal(temp); printHexDigit(d); } return 0; }
Output
Output of the program should be −
24 is even 31 is odd
Advertisements