LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   c++ binary to decimal conversion.. (https://www.linuxquestions.org/questions/programming-9/c-binary-to-decimal-conversion-53152/)

miguetoo 04-02-2003 11:04 PM

c++ binary to decimal conversion..
 
i'm trying to get this binary to decimal convertor working..

could someone help me a tad on this..


Code:

        int argc, count, intconvert, total=0;
        char inputbase1, inputbase2, *intconvertbin, exert;

        do
        {
                printf("\n\nINTEGER CONVERSION PROGRAM\n");
                printf("--------------------------\n\n");
                printf("Base of input (d=decimal, h=hexadecimal, o=octal, b=binary): ");
                scanf("%c", &inputbase1); getchar();

                if(inputbase1=='d')
                {
                        printf("\nNumber: ");
                        scanf("%d", &intconvert); getchar();
                       
                        printf("\nBase of output (d=decimal, h=hexadecimal, o=octal, b=binary): ");
                        scanf("%c", &inputbase2); getchar();
                       
                        if(inputbase2=='d')
                        {
                                printf("\nThe integer %d in decimal is equivalent to %d in decimal.\n\n", intconvert, intconvert);
                        }
                        else if(inputbase2=='h')
                        {
                                printf("\nThe integer %d in decimal is equivalent to %x in hexadecimal.\n\n", intconvert, intconvert);
                        }
                        else if(inputbase2=='o')
                        {
                                printf("\nThe integer %d in decimal is equivalent to %o in octal.\n\n", intconvert, intconvert);
                        }
                }

                else if(inputbase1=='h')
                {
                        printf("\nNumber: ");
                        scanf("%x", &intconvert); getchar();
                       
                        printf("\nBase of output (d=decimal, h=hexadecimal, o=octal): ");
                        scanf("%c", &inputbase2); getchar();
                       
                        if(inputbase2=='d')
                        {
                                printf("\nThe integer %h in hexadecimal is equivalent to %d in decimal.\n\n", intconvert, intconvert);
                        }
                        else if(inputbase2=='h')
                        {
                                printf("\nThe integer %h in hexadecimal is equivalent to %x in hexadecimal.\n\n", intconvert, intconvert);
                        }
                        else if(inputbase2=='o')
                        {
                                printf("\nThe integer %h in hexadecimal is equivalent to %o in octal.\n\n", intconvert, intconvert);
                        }
                }

                else if(inputbase1=='o')
                {
                        printf("\nNumber: ");
                        scanf("%o", &intconvert); getchar();
                        printf("\nBase of output (d=decimal, h=hexadecimal, o=octal): ");
                        scanf("%c", &inputbase2); getchar();
                        if(inputbase2='d')
                        {
                                printf("\nThe integer %o in octal is equivalent to %d in decimal.\n\n", intconvert, intconvert);
                        }
                        else if(inputbase2='h')
                        {
                                printf("\nThe integer %o in octal is equivalent to %x in hexadecimal.\n\n", intconvert, intconvert);
                        }
                        else if(inputbase2='o')
                        {
                                printf("\nThe integer %o in octal is equivalent to %o in octal.\n\n", intconvert, intconvert);
                        }
                }

                else if(inputbase1=='b')
                {
                        printf("\nNumber: ");
                        scanf("%c", &intconvertbin); getchar();
                        for(count = (argc - 1); count < argc; count++)
                                                {
                                if(atoi(intconvertbin[1]) == 1)
                                        total = (total + 1);
                                else if(atoi(intconvertbin[1]) > 1)
                                {
                                        printf("Error! Input must be only 0's or 1's. Try again.");
                                        exit(0);
                                }
                                if(atoi(intconvertbin[2]) == 1)
                                        total = (total + 2);
                                        else if(atoi(intconvertbin[2]) > 1) {
                                                printf("Error! Input must be only 0's or 1's. Try again.");
                                                exit(0);
                                        }
        if(atoi(intconvertbin[3]) == 1)
            total = (total + 4);
        else if(atoi(intconvertbin[3]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[4]) == 1)
            total = (total + 8);
        else if(atoi(intconvertbin[4]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[5]) == 1)
            total = (total + 16);
        else if(atoi(intconvertbin[5]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[6]) == 1)
            total = (total + 32);
        else if(atoi(intconvertbin[6]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[7]) == 1)
            total = (total + 64);
        else if(atoi(intconvertbin[7]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[8]) == 1)
            total = (total + 128);
        else if(atoi(intconvertbin[8]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[9]) == 1)
            total = (total + 256);
        else if(atoi(intconvertbin[9]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[10]) == 1)
            total = (total + 512);
        else if(atoi(intconvertbin[0]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[11]) == 1)
            total = (total + 1024);
        else if(atoi(intconvertbin[11]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[12]) == 1)
            total = (total + 2048);
        else if(atoi(intconvertbin[12]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[13]) == 1)
            total = (total + 4096);
        else if(atoi(intconvertbin[13]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[14]) == 1)
            total = (total + 8192);
        else if(atoi(intconvertbin[14]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[15]) == 1)
            total = (total + 16384);
        else if(atoi(intconvertbin[15]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
        if(atoi(intconvertbin[16]) == 1)
            total = (total + 32768);
        else if(atoi(intconvertbin[16]) > 1) {
            printf("Error! Input must be only 0's or 1's. Try again.");
            exit(0);
            }
                        }
                }
                printf("\nAnother number? (y/n) ");
                scanf("%c", &exert); getchar();
        }
        while(exert == 'y');
        printf("\n\nGoodbye!");
        return 0;
}


GtkUser 04-02-2003 11:40 PM

Binary to decimal:
Code:

#include<iostream>
#include<string>
#include<bitset>
 
using namespace std;
 
int main() {
  cout << "\"1000101011\" as a number : "
      << bitset<100>( string("1000101011") ).to_ulong()
      << endl;
}


miguetoo 04-02-2003 11:43 PM

trying to limit myself by using c instead of c++..

anybody else..?

rmartine 04-02-2003 11:58 PM

Might I suggest a loop to calculate the decimal value. Also.. could you do all your error checking in one shot in a loop then calculate the decimal value rather than error check each bit as you go along?? It could have saved you a lot of typing.

ex.
Code:

for (int i = 0; i < NUM_LENGTH; i++)
{
  if(intconvertbin[i] > 1)
    {
      printf("Error! Input must be only 0's or 1's. Try again.");
      exit(0);
  }
}

now try calculating the number

Code:

for (int i = 0; i < NUM_LENGTH; i++)
{
    number = intconvertbin[i]*pow(2,i) + number;
}

This is just an example but your code could look similar to that. I think it would make your debugging a lot easier. Remember pow() needs double values.

Good Luck

miguetoo 04-03-2003 12:18 AM

okay.. i've looked into what you mentioned and it seems the pow function is kind of new to me.. but after reading some of it in the book, i understand that 'i' increments and 2 is raised to the power of the incremented 'i'..

but i'm not sure what you mean by "NUM_LENGTH" in both examples.. i'm guessing that those two are variables that i have to declare or the input where i would somehow get the length by using strlen().

and last.. you say "calculating the number".. i'm not sure but shouldn't i divide the input.. for ex.

input is 100101011..
i would have to divide intconvertbin (the input) by using
Code:

intconvertbin[i]*pow(2,i) + number
and storing it in the variable "number"..

sorry.. a tad just got to a nab..

rmartine 04-03-2003 01:02 AM

Sorry 'bout that... that was just a quick cookie cutter example to give you another idea on where to go

NUM_LENGTH is the size of your intconvertbin[] array. It seems like yours is 16 or 17. You probably declared the array size somewhere in main().

Quote:

input is 100101011..
i would have to divide intconvertbin (the input) by using

code:intconvertbin[i]*pow(2,i) + number

and storing it in the variable "number"..
I guess I don't understand.. so here is what I was thinking. I put inconvertbin[0] at the right most bit.

LSB: starting at right :)
int number = 0;
number = intconvertbin[0 or i] * 2^(0 or i) + number
so number = 1*2^0 + 0 => number = 1

Bit position 1:
number = intconvertbin[1 or i]*2^(1 or i) + number
so number = 1*2^1 + 1 => number = 3

Bit position 2:
number = intconvertbin[2 or i]*2^(2 or i) + number
so number = 0*2^2 + 3 => number = 3

and so on...

Sorry 'bout the confusion. I think that should work. There is probably a much easier solution. Gtk usually sees them.

miguetoo 04-03-2003 01:16 AM

maybe i'm looking at it wrong myself.. but thanks anyways.. gonna try this tomorrow and see if i can mess around with it..

that one part about the pow() function looks useful..

thanks.. and good night..

miguetoo 04-03-2003 07:03 PM

okay.. here's my whole code..

Code:

/*************************
                Michael Joven
                Co Sci 539
                C R Putnam
                Project 2 - #5
*************************/

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main (void)
{
        int count, intconvert, number, i, NUM_LENGTH;
        char inputbase1, inputbase2, intconvertbin[16], exert;
        NUM_LENGTH='16';

        do
        {
                printf("\n\nINTEGER CONVERSION PROGRAM\n");
                printf("--------------------------\n\n");
                printf("Base of input (d=decimal, h=hexadecimal, o=octal, b=binary): ");
                scanf("%c", &inputbase1); getchar();

                if(inputbase1=='d')
                {
                        printf("\nNumber: ");
                        scanf("%d", &intconvert); getchar();
                       
                        printf("\nBase of output (d=decimal, h=hexadecimal, o=octal, b=binary): ");
                        scanf("%c", &inputbase2); getchar();
                       
                        if(inputbase2=='d')
                        {
                                printf("\nThe integer %d in decimal is equivalent to %d in decimal.\n\n", intconvert, intconvert);
                        }
                        else if(inputbase2=='h')
                        {
                                printf("\nThe integer %d in decimal is equivalent to %x in hexadecimal.\n\n", intconvert, intconvert);
                        }
                        else if(inputbase2=='o')
                        {
                                printf("\nThe integer %d in decimal is equivalent to %o in octal.\n\n", intconvert, intconvert);
                        }
                }

                else if(inputbase1=='h')
                {
                        printf("\nNumber: ");
                        scanf("%x", &intconvert); getchar();
                       
                        printf("\nBase of output (d=decimal, h=hexadecimal, o=octal): ");
                        scanf("%c", &inputbase2); getchar();
                       
                        if(inputbase2=='d')
                        {
                                printf("\nThe integer %h in hexadecimal is equivalent to %d in decimal.\n\n", intconvert, intconvert);
                        }
                        else if(inputbase2=='h')
                        {
                                printf("\nThe integer %h in hexadecimal is equivalent to %x in hexadecimal.\n\n", intconvert, intconvert);
                        }
                        else if(inputbase2=='o')
                        {
                                printf("\nThe integer %h in hexadecimal is equivalent to %o in octal.\n\n", intconvert, intconvert);
                        }
                }

                else if(inputbase1=='o')
                {
                        printf("\nNumber: ");
                        scanf("%o", &intconvert); getchar();
                        printf("\nBase of output (d=decimal, h=hexadecimal, o=octal): ");
                        scanf("%c", &inputbase2); getchar();
                        if(inputbase2='d')
                        {
                                printf("\nThe integer %o in octal is equivalent to %d in decimal.\n\n", intconvert, intconvert);
                        }
                        else if(inputbase2='h')
                        {
                                printf("\nThe integer %o in octal is equivalent to %x in hexadecimal.\n\n", intconvert, intconvert);
                        }
                        else if(inputbase2='o')
                        {
                                printf("\nThe integer %o in octal is equivalent to %o in octal.\n\n", intconvert, intconvert);
                        }
                }

                else if(inputbase1=='b')
                {
                        printf("\nNumber: ");
                        scanf("%c", &intconvertbin); getchar();
                                for (i = 0; i < NUM_LENGTH; i++)
                                {
                                        number = intconvertbin[i]*pow(2,i) + number;
                                        printf("%d", number);
                                }
                }
                printf("\nAnother number? (y/n) ");
                scanf("%c", &exert); getchar();
        }
        while(exert == 'y');
        printf("\n\nGoodbye!");
        return 0;
}

this part :

Code:

                else if(inputbase1=='b')
                {
                        printf("\nNumber: ");
                        scanf("%c", &intconvertbin); getchar();
                                for (i = 0; i < NUM_LENGTH; i++)
                                {
                                        number = intconvertbin[i]*pow(2,i) + number;
                                        printf("%d", number);
                                }
                }

is the part i'm having problems..

anybody can give a hint..

wapcaplet 04-03-2003 07:24 PM

What kind of output (or errors) are you getting?

By the way, to avoid some redundant calculation, you can eliminate the pow() function, and just update a variable each time through the loop:

Code:

int curPow = 1;
for (i = 0; i < NUM_LENGTH; i++)
{
  number = number + intconvertbin[i]*curPow;
  curPow = curPow * 2;
}
printf("%d", number);

This way, curPow holds the current power of two that you want to add (or not add) to the number.

The printf is outside the loop, since presumably you just want the answer at the end, rather than the number in progress (before it is done being calculated).

Also, I haven't looked too closely, but I presume that intconvertbin[] contains bits in ascending order of significance? i.e., that:

intconvertbin = {0, 1, 0, 1}

is equal to 0 ones, 1 twos, 0 fours, and 1 eight (a total of 10).

miguetoo 04-03-2003 07:26 PM

alright.. i'll try that after i finish some other studies i'm doing..

helpful by the looks of your code..

rmartine 04-03-2003 07:49 PM

Man.. I'm sorry for suggesting that.. I'm thinking about a fix. I think I just made more trouble for you. Gimme a couple minutes.

rmartine 04-03-2003 08:14 PM

Ok.. I ran your code and this is what I think is happening... so far

scanf("%c", &intconvertbin); getchar();

This is placing the char you read in to all spaces in intconvertbin
Here is a quick fix to place it in each spot.

scanf("%16c", intconvertbin);

Now if you printf each char you will see whatever you input instead of all 1's or all 0's. Now you can run atoi on each index and use wapcaplet's elegant power solution.

miguetoo 04-03-2003 11:03 PM

okay.. i put wapcaplet's code in and tested it.. but i didn't put in rmartine's "%16c" in the scanf and added the getchar() function.. with the "%16c", the scanf() function will ask about 3 or 4 times input from the user before moving on to the next thing.. so.......

the code i'm using right now is:

Code:

else if(inputbase1=='b')
                {
                        printf("\nNumber: ");
                        scanf("%c", &intconvertbin); getchar();
                        curPow = 1;
                        for (i = 0; i < NUM_LENGTH; i++)
                        {
                                number = number + intconvertbin[i]*curPow;
                                curPow = curPow * 2;
                        }
                        printf("%d", number);

                }

for the else if part.. everything else hasn't been touched..

the output i'm getting from that code is:

Quote:


INTEGER CONVERSION PROGRAM
--------------------------

Base of input (d=decimal, h=hexadecimal, o=octal, b=binary): b

Number: 101011
-97727131
Another number? (y/n)

Goodbye!Press any key to continue
it gets some strange number and skips the (y/n) option..

the code looks like it should work.. but it just seems there's only minor bugs in it.. any takes..?

wapcaplet 04-24-2003 09:49 PM

Why are you using both scanf() and getchar()? I'd think that would grab too many digits and ignore the second one.

Without just telling you how to do it, I'd suggest putting in some additional output. Maybe you could focus first on making sure that the digits are read in correctly. Try reading them in one at a time, and printing out the digit you read. After you make sure that works, then you can add in the conversion code.

Try tracing through it on paper, too. Follow the code through the loop, and write down the values of each variable, and the stuff that would be printed out. That always helps me understand the problem a little better, and helps to find bugs too!


All times are GMT -5. The time now is 03:16 PM.