Difference between revisions of "C Language Practice: Octagonal to Binary Numbers"

From Eric & Company
Jump to navigation Jump to search
(Created page with "== Converting: Octagonal to Binary == * Step 1: Convert octagonal to decimal * Step 2: Convert decimal to Binary <syntaxhighlight lang="c" line style="border: 1px dashed red;"> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int otod(char *o) { int i; int decimal = 0; int place = 0, temp = 0; for (i = strlen(o) - 1; i >= 0; i--) { if ((o[i] >= '0') && (o[i] <= '7')) { temp = o[i] - '0';...")
 
(No difference)

Latest revision as of 21:44, 8 March 2022

Converting: Octagonal to Binary

  • Step 1: Convert octagonal to decimal
  • Step 2: Convert decimal to Binary
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

int otod(char *o)
{
    int i;
    int decimal = 0;
    int place = 0, temp = 0;
    
    for (i = strlen(o) - 1; i >= 0; i--)
    {
        if ((o[i] >= '0') && (o[i] <= '7'))
        {
            temp = o[i] - '0';
        }
        else
        {
            printf("error: not a valid octagonal number\n");
            exit(0);
        }
        decimal += temp * pow(8, place);
        place++;
    }

    return decimal;
}

int main(void)
{
    char o[100];
    printf("Please input an octagonal number: ");
    scanf("%s", o);
    char b[100];

    int quotient, remainder, i = 0, j;
    quotient = otod(o);
    printf("The decimal number for this octagonal number is: %d\n", quotient);

    while (quotient != 0)
    {
        b[i++] = quotient % 2;
        quotient = quotient / 2;
    }

    printf("The binary number for this octogonal number is: ");
    for (j = i - 1; j >= 0; j--)
    {
        printf("%d", b[j]);
    }
    printf("\n");

    return 0;
}