al__nasim

binary to octal and octal to binary

Jul 13th, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. /* C programming source code to convert either binary to octal or octal to binary according to data entered by user. */
  2.  
  3. #include <stdio.h>
  4. #include <math.h>
  5. int binary_octal(int n);
  6. int octal_binary(int n);
  7. int main()
  8. {
  9. int n;
  10. char c;
  11. printf("Instructions:\n");
  12. printf("1. Enter alphabet 'o' to convert binary to octal.\n");
  13. printf("2. Enter alphabet 'b' to convert octal to binary.\n");
  14. scanf("%c",&c);
  15. if ( c=='o' || c=='O')
  16. {
  17. printf("Enter a binary number: ");
  18. scanf("%d",&n);
  19. printf("%d in binary = %d in octal", n, binary_octal(n));
  20. }
  21. if ( c=='b' || c=='B')
  22. {
  23. printf("Enter a octal number: ");
  24. scanf("%d",&n);
  25. printf("%d in octal = %d in binary",n, octal_binary(n));
  26. }
  27. return 0;
  28. }
  29. int binary_octal(int n) /* Function to convert binary to octal. */
  30. {
  31. int octal=0, decimal=0, i=0;
  32. while(n!=0)
  33. {
  34. decimal+=(n%10)*pow(2,i);
  35. ++i;
  36. n/=10;
  37. }
  38.  
  39. /*At this point, the decimal variable contains corresponding decimal value of binary number. */
  40.  
  41. i=1;
  42. while (decimal!=0)
  43. {
  44. octal+=(decimal%8)*i;
  45. decimal/=8;
  46. i*=10;
  47. }
  48. return octal;
  49. }
  50. int octal_binary(int n) /* Function to convert octal to binary.*/
  51. {
  52. int decimal=0, binary=0, i=0;
  53. while (n!=0)
  54. {
  55. decimal+=(n%10)*pow(8,i);
  56. ++i;
  57. n/=10;
  58. }
  59. /* At this point, the decimal variable contains corresponding decimal value of that octal number. */
  60. i=1;
  61. while(decimal!=0)
  62. {
  63. binary+=(decimal%2)*i;
  64. decimal/=2;
  65. i*=10;
  66. }
  67. return binary;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment