Convert between base system in C on Linux

In summary: Octal Value: "); decconversion(num, 8); printf("The decimal value %d in Octal value is %d",num,remainder);
  • #1
ParticleGinger6
32
5
Homework Statement
Your program should convert an integer into another base. The input integer could be in decimal, octal or hexadecimal. The output could be converted into any of the bases. A sample run is below. The user’s response is in boldface.

Base of input integer: Enter d for decimal, h for hexadecimal or o for octal: d
Enter the number: 178
Enter the base of the output (d, h or o): h
The integer 178 in decimal is b2 in hexadecimal
Do you wish to do another? (Y or N): Y

Base of input integer: Enter d for decimal, h for hexadecimal or o for octal: o
Enter the number: 423
Enter the base of the output: d
The integer 423 in octal is 275 in decimal
Do you wish to do another? (Y or N): N
Relevant Equations
Dec to Hex/Oct: divide by the wanted base till the remainder is greater than the dividen.
We have been requested to run this on linux. I am able to read in the original base system and then I am able to enter the number. As soon as I enter the original number the system reads out "Enter the base of the output:" then does not allow the user to enter the second base. Instead it just prints "Do you wish to do another". I have a scanf running for the second base however, it seems to not be wanting to scan anything in.

C:
#include <stdio.h>
#include <string.h>
#include <math.h>

int main(){
    int num, res, j, k;
    long long int n;
    char base1, base2, hex[100];
    char ch;
    do{
        printf("\nBase of input integer: ");
        printf("\nEnter d for decimal, h for hexadecimal or o for octal: ");
        scanf("%c", &base1);
        switch(base1){
            case 'd': printf("\nEnter the number: ");
                            scanf("%d", &num);
                            printf("\nEnter the base of the output (d,h,o): ");
                            scanf("%c", &base2);
                            switch(base2){
                               case 'o': printf("\nOctal Value: ");
                                              decconversion(num, 8);
                                              printf("The decimal value %d in Octal value is %d",num,remainder);
                                              break;
                              case 'h': printf("\nHexadecimal value: ");
                                              decconversion(num, 16);
                                              break;
                            }
                        break;
        case 'h': printf("\nEnter the number: ");
                        scanf("%s", hex);
                        printf("Enter the base of the output (d,h,o): ");
                        scanf("%c", &base2);
                        switch(base2){
                            case 'd': printf("\nDecimal Value: %d",HexToDec(hex));
                                           break;
                            case 'o': printf("\nOctal Value: %d", HexToOct(hex));
                                           break;
                        }
        case 'o': printf("\nEnter the number: ");
                        scanf("%lld", &n);
                        printf("\nEnter the base of the output (d,h,o): ");
                        scanf("%c", &base2);
                        switch(base2){
                            case 'd': printf("\nDecimal Value: %d", OctToDec(n));
                                            break;
                            case 'h': printf("\nHexadecimal Value: %d", decconversion((OctToDec(n)), 16));
                                            break;
                        }
                        break;
            break;
        }
        printf("\nDo you wish to do another Y/N: ");
        scanf("%c", &ch);
    }
    while(ch=='y' || ch == 'Y');
    return 0;
}

int decconversion(int num, int base){
    int remainder = num%base;
    if(num==0){
        return;
    }
    decconversion(num/base,base);
    if(remainder <10){
        printf("%d", remainder);
    }
    else {
        printf("%c", remainder - 10+'A');
    }
}

int HexToOct(char hex[]){
    int i, len, dec = 0, oct =0;
    for(len=0;hex[len]!='\0'; len++);
    for(i=0; hex[ i]!='\0'; i++, len--){
        if(hex[ i]>='0' & hex[ i]<='9'){
            dec =dec+(hex[ i]-87)*pow(16, len-1);
        }
    }
    i =1;
    while(dec!=0){
    oct = oct +(dec%8)*i;
    dec = dec/8;
    i = i*10;
    }
    return oct;
}

int HexToDec(char* hex){
    int dec =0, base = 1, i, d;
    char c;
    i = strlen(hex)-1;
    while(i>=0){
        c = *(hex+i);
        if(c>='A' && c<='F')
            d = 10+c-'A';
        else if(c>='a' && c<='f')
            d = 10+c-'a';
        else
            d = c-'0';
        dec +=d*base;
        base*=16;
        i--;
    }
    return dec;
}

int OctToDec(int oct){
    int dec = 0, base =1;
    int t;
    t = oct;
    while(t>0){
        dec+=(t%10)*base;
        t/=10;
        base*=8;
    }
    return dec;
}
 
Last edited by a moderator:
Physics news on Phys.org
  • #2
Your posted code is too hard to follow.
1) You should use levels of indentation to make it clear where the nested {} sections begin and end. If you have that in the code, use the code option to post it correctly.
2) You can use the debugger to go step-by-step through an execution. That will tell you exactly where things go wrong. There is a learning curve to using the debugger that is well worth the effort. Barring that, a few printed "I am on line ##" should help you to narrow down the problem.
 
  • #3
FactChecker said:
Your posted code is too hard to follow.
Agree. I have enclosed the code with code tags, and have attempted to indent to make it more readable. @ParticleGinger6, please use code tags -- there is a brief description in the first article of this forum section.

Also, be cautious when using an array index i. An expression such as hex[ i], will cause problems unless there is an added space before i. The reason for this is that browsers will interpret an i in brackets as a cue to render everything that follows in italics.
For a similar reason, you shouldn't use b in brackets as an array index -- the browser will turn everything that follows into bold.
 
Last edited:
  • Like
Likes FactChecker
  • #4
ParticleGinger6 said:
As soon as I enter the original number the system reads out "Enter the base of the output:" then does not allow the user to enter the second base. Instead it just prints "Do you wish to do another". I have a scanf running for the second base however, it seems to not be wanting to scan anything in.
In your code, you ask the user to enter a character for the base of the input (d, o, or h), then the number, and finally a character for the base of the output. The reason your code doesn't let you enter the character for the output base is that when you enter the number (in the 2nd scanf call), the input buffer contains the characters for the number, plus the newline character produced by hitting the Enter key.

The newline character can't be part of the number, so it sits in the input buffer, ready for the next call to scanf. On the third call to scanf for the base for the result, base2 gets set with the newline character, and your program doesn't let you do any input.

One thing that you could do is to call getchar() after the 2nd scanf call, to consume the newline character. Another thing you could do is to flush the input buffer, using this code:fflush(stdin);
You don't need to add any more #include files -- fflush and getchar() are declared in stdio.h, and stdin, the standard input stream, is declared in a header that stdio.h includes.
 
  • Like
Likes FactChecker

FAQ: Convert between base system in C on Linux

How do you convert a number from one base system to another in C on Linux?

To convert a number from one base system to another in C on Linux, you can use the atoi() function to convert the number from its original base to decimal, and then use itoa() to convert it from decimal to the desired base system. Alternatively, you can use the strtol() function to convert the number directly to the desired base system.

Can you explain the process of converting between base systems in more detail?

Converting between base systems involves dividing the original number by the base of the new system and keeping track of the remainders. The remainders are then combined in reverse order to form the new number in the desired base system. For example, to convert from binary to decimal, you would divide the binary number by 2 and keep track of the remainders, which would then be combined in reverse order to form the decimal number.

Are there any built-in functions in C that can help with converting between base systems?

In addition to the atoi(), itoa(), and strtol() functions mentioned earlier, C also has the sprintf() function which can be used to convert a number to a string in a specific base system. There are also various libraries available that offer more advanced conversion functions for different base systems.

Is it possible to convert between non-standard base systems, such as base 3 or base 16, in C on Linux?

Yes, it is possible to convert between non-standard base systems in C on Linux. You can use the itoa() or strtol() functions with the desired base as the second argument. For example, to convert a number to base 3, you would use itoa(num, str, 3).

Are there any common errors to watch out for when converting between base systems in C on Linux?

One common error is forgetting to account for the difference in characters between different base systems. For example, the digits 0-9 are the same in all base systems, but the letters A-F are used for the digits 10-15 in hexadecimal. Another error is not properly handling negative numbers, as the process of converting to a different base system may produce a negative result. It is important to thoroughly test your code and account for all possible scenarios to avoid errors.

Similar threads

Replies
1
Views
9K
Replies
4
Views
1K
Replies
1
Views
4K
Replies
1
Views
2K
Replies
4
Views
2K
Replies
4
Views
8K
Replies
1
Views
1K
Back
Top