Search code examples
cintegeroctal

How would I perform octal arithmetic using integer variable?


Say I want to add two octal values, 0144 to 0144, in C.

int a = 0144;
int b = 0144;
int result = a + b;
printf("%d, %o", result, result);
> 200, 310

In my program, a hex value is entered, this is converted to a octal value, but the conversion leaves the result looking like an integer in base 10 rather than base 8.

For example:

int oct = convertHexToOct(64)
printf("%d, %o", oct, oct);
> 144, 220
int result = oct + oct;
printf("%d, %o, result, result);
> 288, 440

So the decimal representation of the oct variable is really the octal value of the desired integer. This means any arithmetic done to with this variable will be done in base 10, which is not what I want to do.

What I basically would want to do, ideally, is something like

int intAsOct = "0" + oct;
int octalResult = intAsOct + intAsOct;

But this obviously will not work. So the root of the question is, how do I treat an integer variable that was saved without the leading 0 as an octal for use in arithmetic?


Solution

  • Per your comment:

    How do I take a base10 integer, "144" and have C treat it as a base8 integer, "0144"

    you can do it manually, but the easiest way is to convert it via the standard library string functions, like so:

    #include <stdio.h>
    #include <stdlib.h>
    
    int dec_to_oct(const int dec)
    {
        char buffer[64];
        char * endptr;
    
        /*  Convert number to decimal string representation  */
    
        sprintf(buffer, "%d", dec);
    
        /*  Convert decimal string representation back as octal  */
    
        long l = strtol(buffer, &endptr, 8);
        if ( *endptr != '\0' ) {
            fprintf(stderr, "Error! Could not convert decimal %d to octal.\n", dec);
            exit(EXIT_FAILURE);
        }
    
        return (int) l;
    }
    
    int main(void)
    {
        int num = 144;
        printf("Before conversion: %d, %#o, %#x\n", num, num, num);
    
        num = dec_to_oct(num);
    
        printf("After conversion: %d, %#o, %#x\n", num, num, num);
    
        dec_to_oct(999);    /*  This will fail  */
    
        return 0;
    }
    

    with output:

    Paul@Pauls-iMac:~/Documents/src/sandbox$ ./dec_to_oct
    Before conversion: 144, 0220, 0x90
    After conversion: 100, 0144, 0x64
    Error! Could not convert decimal 999 to octal.
    Paul@Pauls-iMac:~/Documents/src/sandbox$