LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 04-02-2003, 11:04 PM   #1
miguetoo
Member
 
Registered: Mar 2003
Location: soCal..
Distribution: lfs server.. slackware workstation..
Posts: 58

Rep: Reputation: 15
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;
}
 
Old 04-02-2003, 11:40 PM   #2
GtkUser
Member
 
Registered: Sep 2002
Location: Canada
Distribution: Redhat 9.0
Posts: 637

Rep: Reputation: 30
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;
}
 
Old 04-02-2003, 11:43 PM   #3
miguetoo
Member
 
Registered: Mar 2003
Location: soCal..
Distribution: lfs server.. slackware workstation..
Posts: 58

Original Poster
Rep: Reputation: 15
trying to limit myself by using c instead of c++..

anybody else..?
 
Old 04-02-2003, 11:58 PM   #4
rmartine
Member
 
Registered: Dec 2002
Location: San Luis Obispo, CA
Distribution: Fedora Core 3
Posts: 618

Rep: Reputation: 30
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
 
Old 04-03-2003, 12:18 AM   #5
miguetoo
Member
 
Registered: Mar 2003
Location: soCal..
Distribution: lfs server.. slackware workstation..
Posts: 58

Original Poster
Rep: Reputation: 15
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..

Last edited by miguetoo; 04-03-2003 at 12:28 AM.
 
Old 04-03-2003, 01:02 AM   #6
rmartine
Member
 
Registered: Dec 2002
Location: San Luis Obispo, CA
Distribution: Fedora Core 3
Posts: 618

Rep: Reputation: 30
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.
 
Old 04-03-2003, 01:16 AM   #7
miguetoo
Member
 
Registered: Mar 2003
Location: soCal..
Distribution: lfs server.. slackware workstation..
Posts: 58

Original Poster
Rep: Reputation: 15
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..
 
Old 04-03-2003, 07:03 PM   #8
miguetoo
Member
 
Registered: Mar 2003
Location: soCal..
Distribution: lfs server.. slackware workstation..
Posts: 58

Original Poster
Rep: Reputation: 15
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..
 
Old 04-03-2003, 07:24 PM   #9
wapcaplet
LQ Guru
 
Registered: Feb 2003
Location: Colorado Springs, CO
Distribution: Gentoo
Posts: 2,018

Rep: Reputation: 48
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).
 
Old 04-03-2003, 07:26 PM   #10
miguetoo
Member
 
Registered: Mar 2003
Location: soCal..
Distribution: lfs server.. slackware workstation..
Posts: 58

Original Poster
Rep: Reputation: 15
alright.. i'll try that after i finish some other studies i'm doing..

helpful by the looks of your code..
 
Old 04-03-2003, 07:49 PM   #11
rmartine
Member
 
Registered: Dec 2002
Location: San Luis Obispo, CA
Distribution: Fedora Core 3
Posts: 618

Rep: Reputation: 30
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.
 
Old 04-03-2003, 08:14 PM   #12
rmartine
Member
 
Registered: Dec 2002
Location: San Luis Obispo, CA
Distribution: Fedora Core 3
Posts: 618

Rep: Reputation: 30
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.
 
Old 04-03-2003, 11:03 PM   #13
miguetoo
Member
 
Registered: Mar 2003
Location: soCal..
Distribution: lfs server.. slackware workstation..
Posts: 58

Original Poster
Rep: Reputation: 15
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..?
 
Old 04-24-2003, 09:49 PM   #14
wapcaplet
LQ Guru
 
Registered: Feb 2003
Location: Colorado Springs, CO
Distribution: Gentoo
Posts: 2,018

Rep: Reputation: 48
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!
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Decimal Symbol - does it exist??? ipreuss Linux - General 2 03-25-2005 12:13 PM
cout conversion to binary... audibel Programming 3 03-12-2005 07:06 AM
How to use decimal numbers in in shell scripts a1ex_007 Programming 6 03-11-2005 09:05 AM
Decimal to binary maldini1010 Programming 6 02-01-2005 04:03 PM
decimal comma notation conversion to dot? heaslein69 Linux - Software 2 01-25-2002 04:05 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 02:15 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration