Question

converting binary to decimal

Asked by: buckeyes33

Before you ask.  This is school work, saying that I don't want the answer.  I would however like some help in solving my problem.  I know how to convert binary to decimal on paper.  Meaning I can do this.  EX: 11010 = 0 x 2^0 + 1 * 2^1 + 0 x 2^2 + 1 x 2^3 + 1 x 2^4 = 26.  I can do that and understand it fine.  here is what I am trying to figure out.

How to convert binary to decimal using integers.  I have figured out how to convert them by using charactor arrays.  I have also figured out how to convert from decimal to binary by using integers.  I have just not figured out how to go from binary to decimal using integers rather the arrays.
Why do I want to do it that way you might ask?  Well my professor said that the project would be easier that way.  In fact it would be b/c of the way the rest of the project is set up.  If I can figure out how to do it doing integers it would save me some time.  Points will be given on how much help you give and how revelant the post(s) is/are.  I will not accept anyone's post that post the answer.  

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-11-28 at 17:06:18ID20811309
Tags

binary

,

decimal

,

c

,

convert

Topics

C Programming Language

,

CYGWIN

Participating Experts
4
Points
500
Comments
35

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Conversion Binary <-> Decimal
    Hi I need two simple functions: 1 - Convert Binary to Decimal and returns this value 2- Convert Decimal to Binary and returns this value Thanks
  2. binary to decimal
    how do you convert binary to decimal in visual basic 6.0?
  3. Binary to Decimal
    I'm new to Java, I wrote a program to convert Binary to Decimal, and it work fine. But if my input other than "1" or "0", the program given a run time error. how can i check the input before it proceed to with the conversion? I'm using While statement for...
  4. Decimal To Binary
    Hi, I've written a function to convert a Decimal to a Binary String. It works perfectly. But I was wondering if there was a more efficent way to do this. This was the most efficent method I could think of. Suggestions please on optimization. Public Function Dec2Bin(dec As In...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: shivsaPosted on 2003-11-28 at 17:10:30ID: 9840720

In the C programming language, an integer is converted from binary to decimal when the %d specifier is used in printf(), sprintf() or fprintf(). %o is used to convert a number to its octal representation, and %x is used to get the hex representation.

 

by: shivsaPosted on 2003-11-28 at 17:16:54ID: 9840732

 

by: KdoPosted on 2003-11-28 at 19:12:41ID: 9841074

Hi Buckeyes33,

Converting values is a popular theme here on the boards.  One of the most common traits of these questions is that in asking to convert from binary to decimal, what the poster really wants (and needs) is to convert from binary to display (ASCII).  Your questions sounds like it fits into this category so I'm going to answer based on that inference.

First, all integer values are binary to the computer.  It doesn't matter whether you're dealing with int, short, or long values.  They are always binary, which is the computer's "native" representation.

You and I don't think in binary.  (Well, we can, and sometimes do, but it's not the way our minds have been trained to think.)  We do think in decimal.  Using your example above, if we were to attempt to purchase 26 items from the grocery store no one would think much of it.  But if we were to discuss the matter with a cashier and explain that the reason that we bought 11010 items is because their their 10 for 1 sale made us buy twice the number that we had intended so we bought 11010 instead of 1101, we probably wouldn't ever get the transaction completed accurately.

But that's the way computers "think".  We think in decimal so whenever we have our computer programs display a value it is usually converted to decimal display (ASCII).

Making the conversion is really easy.  You asked that the answer not be posted as a program (code).  I'll do my best to comply, though it's tougher this way.  The actual code is only about 6 lines of code.  (Well, 110 lines in binary.  :)  Here are the steps that you need to follow to generate your own conversion:

First create a character buffer for the assembly.  Initialize the entire buffer to blanks, except the last character which must be zero to terminate the string.

Then create a character pointer and point it to the LAST space in the string.

Using the % function, take the modulo 10 remainder of the value to be converted.  Using your sample value of 26 you will get 6.  Store the 6 in the location pointed to by the character pointer.  But you cannot store the binary 6, you must display the ASCII value for 6.  You can generate this by adding the binary value of 6 to the binary value of the ASCII 0.  (Value + '0'.)

Divide the value to be converted by 10.  If the new value is zero, the conversion is complete and the character pointer points to the converted value.  With our sample value of 26, of course the result is 2.

Decrement the character pointer so that it now points to the position where we will store the next digit.

Loop back up and take the next modulo 10 value.

That's it.  That's all there is to converting binary to decimal display (ASCII).

Hope that I understood the question correctly and gave you a response in the form that you need,
Kent

 

by: sunnycoderPosted on 2003-11-28 at 23:03:24ID: 9841555

>I have just not figured out how to go from binary to decimal using integers rather the arrays.

Kent:
>First create a character buffer for the assembly.
Looks like you missed it this time ;o)

Buckeyes33:
>I have just not figured out how to go from binary to decimal using integers rather the arrays.
This should be pretty simple ...
1. you know that binary number is nothing but a sequence of 0s and 1s .... to get equivalent decimal, each 0 and each 1 is multiplied by some weight depending on its position in the sequence...

2. you also know that & is the bitwise operator and ( number & 0x1 ) will give you the least significant bit of number

3. you also know that we have a right shift operator in C

putting 2 and 3 together, we can easily determine if LSB of a given binary number is 0 or 1 ... we can also right shift the number to examine the next bit and then next and so on ...

If I have 32 bit int then 32 right shifts in a loop will allow us to examine all the bits ... only problem is to determine the weight for each bit, multiply each bit by its weight and keep the cumulative sum... Since we are doing all manipulation in the loop, we can easily get the weight by initialzing weight to 1 and multiplying by 2 at each iteration ....

So we have:::
initialize weight to 1
initialize cumulative to 0
for all bits in number do
          calculate ( number & 0x1 )
          multiply this by weight
          add it to cumulative sum
          multiply weight by 2
          right shift number by one bit
done
your equivalent decimal is in cumulaive sum

Cheers!
Sunny

 

by: KdoPosted on 2003-11-29 at 06:40:49ID: 9842324

Hi MR Sunny,  :)

I didn't miss it.  I'm assuming that the poster wants to convert the value to decimal before displaying it.  He strongly suggests that he does.  Using a buffer with a "current" pointer eliminates the array notation.  Also, we don't know where he wants to avoid array references.  It could be that he also wants to eliminate an array to convert the binary to ASCII.

Hi Buckeyes33,

There is another applicable way to accomplish this and it works for converting to any base (or even displaying the value in the ASCII equivalent of its binary value).  It's with recursion.  But if your current assignment is to convert binary to display, I doubt that the classroom discussion has covered much of recursion.  Still, here goes:

Create a function that will convert a single digit.  Let's call it DisplayAnyBase().  The function has two parameters:  The value to convert and the base to which it will be converted.

Within the function, perform the two basic conversion operations:  Take the modulo(value,base) with the % operator and then divide the original (passed) value by the base.

If the new value is non-zero, call the function again (from within the function) passing the new value and the base.  (Recursively, this will continue until a remainder of zero is found.

Now, (still coding within the function) display the value that was computed by the modulo(value,base) calculation.  If the base is 10 or less, you can simply add this value to '0' to get the ASCII (displayable) value.  If the base is greater than 10, for example 16 (hex), you'll need to convert values of 9 or less by adding '0'.  Values of 10 or greater will convert by adding 'A' and subtracting 10.  (Think about it a second....)

The function now does a return and if there are more digits to display the previous iteration of the function will display the next digit.

Since recursion is probably new to you, here's a diagram of what happens.  No code!  :)   To start with, we have to understand that all of these are equivalent:

DisplayAnyValue (125, 10);
DisplayAnyValue (0x7D, 10);
DisplayAnyValue (0175, 10);
DisplayAnyValue (bin(1111101), 10);

They all pass the same value for the first argument.  The compiler takes care of converting the value into its machine equivalent.  But we're people, not machines, so let's use the top one.  It will make the demonstration the easiest.

Value Passed    Base   Saved Digit   New Value
  125                 10           5                12
   12                  10           2                1
    1                   10           1                0


Look at the "Saved Digit" column.  What you see is the individual digits of the original value, but in reverse order!  (The original value of 125 produced the digits 5, 2, and 1.)  You'll find that this occurs in almost every conversion method that you'll employ.  This is why the character buffer method in my first post had you decrement the pointer -- you're essentially moving right to left.  It's also why the recursion method works like it does.  It picks off the digits one-by-one and only when the last digit is found does it go about displaying them.

Good Luck,
Kent

 

by: buckeyes33Posted on 2003-11-29 at 07:53:25ID: 9842544

I have to say that sunnycoder has the correct assumption.  I want to convert from binary to decimal.  I don't want to print the ACSI euivilant to the binary number.

For one part of my project I have to ask the user to input a binary number, two of them actually.  I then have to convert them to decimal, add them, and then convert them back to binary and then print the binary.

When I get some time I will try to figure it out using the method sunny has given.That is the only problem I am having.  Unless someone knows how to make sure that I binary is actually a binary number.  I have to test for a binary number that the user has entered.  If the number entered is not binary then I have to ask the user again for the binary numbers.  by doing this I am going to use a do-while loop and put the user prompts inside the do-while loo and then test to see if the number entered is binary.

thanks for the help.

 

by: KdoPosted on 2003-11-29 at 09:58:02ID: 9842899

Hi Buckeyes,

> I want to convert from binary to decimal.  

The computer keeps integers in binary form.  Whether it's base 2, 3, 10, 16 or anything else doesn't matter.  The computer knows what it's internal representation is and how to use it.  (More on this later -- it's the underlying theme of the question.)

> I don't want to print the ACSI euivilant to the binary number.

Sure you do.  If you want to put an answer on the screen, it must be converted to a displayable value.  You do this by converting the binary value of each digit (which is the machine readable form) to the ASCII equivalent (which is the human readable form).

To test this, try this simple program.  (This code isn't the answer to your original question, just a demonstration of how binary and ASCII differ.)

#include <stdlib.h>

int BinaryValue = 1;

main ()
{
  puts ("Binary 1 = ");
  putch (BinaryValue);
  putch ("\n");       /* new line  */

  puts ("Display 1 = ");
  putch (BinaryValue + '0');
  putch ("\n");
}

> I have to ask the user to input a binary number, two of them actually.

The user inputs strings of ASCII characters!  You then convert the ASCII characters to binary, the machine's "native" representation.

>  I then have to convert them to decimal.

After you ask for a value and the user enters one, you have an ASCII string!  Pretend for a second that the User entered 1010.  If we think of 1010 as a binary value then it has an equivalent value of 10 decimal (base 10).  But what you'l find is that the actual bit stream that your C program has stored is 0011000100110000001100010011000000000000, the binary equivalent of the character string "1010", which is 0x3130313000.

This character string must be converted to it machine form equivalent before the computer can use it.  We must convert the string "1010" to the 4-bit value 1010.

> and then convert them back to binary and then print the binary.

Nope.  You convert them to ASCII before you print them.  They are already in binary.  Go back to the short program 2 bullets back.


Part of the confusion here is terminology.  You're using the term "binary" to mean "base 2".  Granted, one definition of binary IS "base 2", but the most common definition (within computer circles) is the machine readable form of a number that can be used in native calculations such as add, subtract, and multiply.

So going back to the original problem, here are the steps that you'll need to program:

1)  Display a nice message for the user that he is to input a binary value.  (In this case, the term "binary" is used to tell the user that the value must contain only 1s and 0s.)

2)  Read the input value.  (It is in the form of a string!!!!!)

3)  Convert the string to its machine readable equivalent and store it in an int.

4)  Repeat steps 1 through 3 for the second value.

5)  Add the two int values.

6)  Convert the answer back to a characters string of 1s and 0s.

7)  Display the string created in step 6.

Kent

 

by: buckeyes33Posted on 2003-11-29 at 11:07:58ID: 9843127

I think that you might both be correct.  It is just two different ways of doing it.  I don't have time to look into it and probably won't for two days, so be patient please.  Your help is very much appriecated.


to get rid of the lack of confussion of what I am trying to do here is a link.  It is part 2 of the link.
http://web.ics.purdue.edu/~cs158/proj/p4.pdf

 

by: KdoPosted on 2003-11-29 at 17:47:14ID: 9844144


I love it when a plan comes together....  :)

From my previous examples, everything still holds true EXCEPT that you will not need (or be allowed to) convert the string to/from binary!

So here's the scoop:

1)  Display a nice message for the user that he is to input a binary value.  (In this case, the term "binary" is used to tell the user that the value must contain only 1s and 0s.)

2)  Read the input value into a string.  Note that you are going to want to scan the string backwards.  You can do this by counting characters, or by setting the first character of the string to 0 and starting the input at the second character.  I strongly recommend that you choose the second option.  (You also need to check the string to make sure that all characters are "0" or "1".)

You are going to scan the string backwards because that is the way we add we usuallyl add so that we can keep track of the carry with the least amount of overhead.  In a normal (base 10) addition, you might see something like this:

  8094
+  236
--------

The first thing that you'll do is add the 4 and the 6, generating 10.  Drop the 0 and carry the 1.  You next add 1, 9, and 3 generating 13.  Drop the 3 and carry the 1, etc....

Adding binary numbers works the same way.

   1110110110111
+                 1001
---------------------

You need to "right align" the data and work right to left.  Add 1 and 1, generating 10.  Drop the 0 and carry the 1.  You next add 1, 1, and 0 generating 10.  Drop the 0 and carry the 1, etc....

3)  Display a nice message for the user that he is to input another binary value.

4)  Read the input value into another string.  Do NOT overwrite the first string!!!!  You will also need to scan this string backwards.  The same method that you chose for step 2 will also be applied here.

5)  The program should have created a buffer for the conversion.  (Buffer[1024] is fine.  If you want to create the buffer "on the fly" that is guaranteed to be large enough, use malloc() to create a buffer that is at least 2 bytes longer than the longer of the two inputs.  Set the LAST character of the buffer to 0.  This is the string terminator.  Back up one character and set a "0" into the buffer.  If you decide to allow the null string as a legal value for zero, you'll want a zero in the output buffer so that you can display zero.  null might mean zero on input, but you'll want to display a zero on output.

6)  Set pointers to the LAST character of the two input values.

7)  Set a pointer to the zero that you put into the output buffer.

8)  Initialize the "carry" flag to 0.

8)  Now start "adding", right to left.  Remember that you're adding characters, not binary (machine readable) values!  And don't forget to add in the carry flag, and genrate a carry flag, too!!!!

9)  After you create an output digit, you need to decrement the input pointers.  This might prove awkward since you only want to decrement an input pointer if the pointer points to a non-null value.  (This is why I urged you to start the input string with a zero.)  If in step 2 you decided to count characters, you need to perform this same check, but based on characters processed.

10)  if there are more characters to process, decrement the output pointer.  Remember that even if you've used all of the characters in strings 1 and stings 2, if the carry flag is 1, you're not done!!!

11)  Repeat steps 8 through 10 until both strings are exhausted.

Your output pointer now points you to the correct output string.  Just display it and you're done!


Good Luck,
Kent

 

by: guynumber5764Posted on 2003-12-01 at 12:25:04ID: 9852726

sscanf("%b") ?  (just kidding)

I would say that sunny's solution is the one you are looking for.  It never hurts to have a good handle on the bitwise operators regardless.

 

by: KdoPosted on 2003-12-01 at 12:33:58ID: 9852788


Sunny's approach works for displaying values, but doesn't deal with reading them or performing math on "binary strings".

Kent

 

by: buckeyes33Posted on 2003-12-01 at 18:56:59ID: 9855189

I recently found out that my professor had went over the conversion in class and it is in my notes.  Here is what he has put.

int toDecimal(int binary)
{
        int power = 0;
        int decimal = 0;
        int num;

        while (binary > 0)
        {
                num = binary % 10;
                decimal = decimal + num * (int) pow(num * 2, power++);
                binary = binary / 10;
        }

        return(decimal);
}


I will only need to use what is in the while loop.  However, because this is know information by everyone in the class I an not sure if I want to use it.  What do you think?

Kdo
I don't want to use strings in part 2 of the project.  As your comments have used strings.  

 

by: guynumber5764Posted on 2003-12-01 at 20:51:35ID: 9855725

Ahhh.  It all comes clear.

You are representing (101)base2 as (101)base10.
In that case, there's not much way around your teachers code:
(x >> 1) becomes (x / 10).
(x & 1)  doesn't have to change but ( x % 10) means any non-zero digit will count as a 1 which isn't a bad thing here.

The best single improvement I can see is removing the pow() call:  there is a very simple and elegant way to do it. ;)

E.

 

by: guynumber5764Posted on 2003-12-01 at 20:53:02ID: 9855731

...assuming you are still using a loop.

 

by: sunnycoderPosted on 2003-12-01 at 21:26:53ID: 9855859

>Sunny's approach works for displaying values, but doesn't deal with reading them or performing math on "binary strings".
that was what was intended Kent :-p

buckeyes33,
this is pretty close to what I had suggested ... the basic idea is to examine each bit from LSB end ...
Multiply the bit by its equivalent weight/face value and add the result it to cumulative sum
In the end you will have the result in the cumulative sum.

In my suggestion, bits were examined by sifts, here you get them using % and this difference is due to difference in representation.

>However, because this is know information by everyone in the class I an not sure if I want to use it.  What do you think?
Programming is about doing a job in best (optimal) way possible and not in some unique twisted way ... Your prof discussed it in class and told you to use it ... then it does makes good sense to use it

 

by: buckeyes33Posted on 2003-12-01 at 22:07:45ID: 9856017

>Programming is about doing a job in best (optimal) way possible and not in some unique twisted way ... Your prof discussed it in class and told you to use it ... then it does makes good sense to use it

It is just the fact that all the programs summited are ran through software to see if they are similar.  If the similarity is too high, then there is questions.   I will have about 20 lines of code that could be very similar to someone elses.  I am getting 20 due to the fact that how to check if an int was binary was in the same notes.  Would you think that it would be a problem or would using the code not be a problem.

 

by: sunnycoderPosted on 2003-12-01 at 22:11:59ID: 9856033

Now that is a tough one ... Depends on how intelligent the tool is (will changing names of variables help ? ) .. also how big is the overall program ... as you said, this is a small part ... If 30 odd lines in a 1000 line program are similar, I do not think it should be a big issue ... but you are in a better position to make such judgements as you know it best

 

by: buckeyes33Posted on 2003-12-01 at 22:22:07ID: 9856081

>will changing names of variables help ?
no

my whole program is 408 lines so 20 lines or so is 12 %.  
As of know I am going to use it.  I still have a view days to change my mind.  I currently have to get my program to compile and see how the other part of the program works.

 

by: sunnycoderPosted on 2003-12-01 at 23:13:17ID: 9856288

a slight improvement and some difference can be created by removing pow()
initialize weight to 1
use * weight in place of * pow(...)
in each oteration weight = weight * 2 ...

Apart from that, given this representation, I am afraid you should be using the same method ...

Ofcourse you can always turn to C library and strings
sprintf ( string, "%d", number );
converted = strtol ( string, NULL, 2 );

 

by: buckeyes33Posted on 2003-12-02 at 06:17:06ID: 9858313

>Of course you can always turn to C library and strings
can't it is a requirement for the project

so if i changed the code it would look like this.

int toDecimal(int binary)
{
        int power = 0;
        int decimal = 0;
        int num;
        wieght = 1;
        while (binary > 0)
        {
                num = binary % 10;
                decimal = decimal + num * (wieght * 2)(num * 2);
                binary = binary / 10;
        }

        return(decimal);
}

 

by: buckeyes33Posted on 2003-12-02 at 16:11:44ID: 9862983

Was the above correct?

I now need some help converting decimal to binary.  Agian I can not figure it out without using arrays. Here is what i am trying to do.


binary = (last number) * pow(10, i++);

but after that I am lost.

 

by: KdoPosted on 2003-12-02 at 18:44:25ID: 9863682

Hi Buckeyes33,

Please go back and read the assignment one more time.  You'll see that option 1 tells you to add two binary numbers using character arrays.  Option 2 tells you to convert to decimal, add, and convert back.  The outlines that I've given you tell you the steps to do just that.

Your toDecimal() function has a major problem in that you are passing an int to the function.  An int is the binary representation of an integer value in machine readable form.  Converting it to decimal to return another int is a meaningless operation since the int that you are passing to the function is ALREADY in a form suitable for calculating.

What you really want to do is convert the input STRING to binary.  (I described this in my second response.)  You asked that code not be posted, but the conversion is easy enough that I don't feel that providing you with a few lines of C code would violate the membership agreement or give you an unfair leverage with your assignment.  Still, if you don't want to see the source code I'll place it at the very bottom of this reponse so that you can ignore it.

Part II of your assignment is described in page 3.  It says that you can read in the numbers as an int or long.  This will save you the trouble of converting a character string to a binary value.  Here's a hint:  You can use scanf() to read the int value, but scanf() is a poorly designed function.  An equivalent that works much better is to read the input with fgets(), then call sscanf() to convert the input to a binary value.


Again, Good Luck.  Code to follow.
Kent

/*
  String to Decimal -- Convert a string to a binary int value
*/

int StringToDecimal (char *string)
{
  int Value = 0;     /*  Initialize the converted value to 0  */

  while (*string)   /*  If *string is non-zero, a character is present.  I.E.  we're not at end-of-string  */
    Value = Value * 10 + (*string - '0');  /*  Multiply the partially converted value by 10 and add the current digit  */

  return Value;
}

 

by: buckeyes33Posted on 2003-12-02 at 18:54:50ID: 9863725

>Converting it to decimal to return another int is a meaningless operation since the int that you are passing to the function is ALREADY in a form suitable for calculating.

That is one the requirements of the assignment. I know it is stupid, but it is his way of trying to get something to stick in us.  My professor just happens to be my TA (which is nice a professor calls me by name, WOW)  also so I asked him and that is what he wants, even if it does not print anything.  He still wants to be able to see the code and grade it.

 

by: buckeyes33Posted on 2003-12-02 at 18:55:57ID: 9863729

You might not be able to tell that unless you run the sample program.

 

by: sunnycoderPosted on 2003-12-02 at 22:01:07ID: 9864518

int toDecimal(int binary)
{
       int power = 0;
       int decimal = 0;
       int num;
       wieght = 1;
       while (binary > 0)
       {
               num = binary % 10;
               decimal = decimal + num * wieght ;
               binary = binary / 10;
               wieght = wieght * 2;
       }

       return(decimal);
}

 

by: buckeyes33Posted on 2003-12-02 at 22:46:13ID: 9864717

I see what wieght is used for now.
Ok for the decimal to binary:  I want to do something like this.

void tobinary(decimal);
int num;
    printf("\nThe sum of the two binary numbers is: ");

   while(decimal > 0)
   {
        decimal = decimal / 2;
        num = decimal  % 2;
       
        printf("%d", num);
    }
 
   printf("\n");
}
       

 

by: buckeyes33Posted on 2003-12-02 at 22:48:20ID: 9864725

Sunnycoder or Kdo  would either one of you two be willing to look at my whole program off of the thread.  I am getting some compiling errors that I know deal with how I am passing my variables on part 1, but I don't know how to fix them.

 

by: sunnycoderPosted on 2003-12-02 at 22:53:41ID: 9864744

void tobinary(decimal);
int num;
   printf("\nThe sum of the two binary numbers is: ");

  while(decimal > 0)
  {
       decimal = decimal / 2;              =====  shouldn't order of these two statements be reversed ?
       num = decimal  % 2;                =====
     
        printf("%d", num);
   }

   printf("\n");
}

If you feel that errors cannot be pointed out/corrected by posting code snippets and error messages
and if your code is indeed that big that it cannot be posted here, my mail id is in my profile

 

by: sunnycoderPosted on 2003-12-03 at 00:06:45ID: 9864995

ok ... found the error list as well as reason for your reluctance in posting code here
you can mail the code to me (and I'll try to resist selling it to your classmates <evil plotting grin>)

I am posting some likely causes ... If that does not help, mail me

project4.c: In function `option1':
project4.c:93: parse error before `;'
project4.c:95: parse error before `;'
syntax errors, most likely missing , or " or ) or some other punctuation mark

project4.c:121: warning: passing arg 1 of `checkforBinary' makes integer from pointer without a cast
project4.c:121: warning: passing arg 2 of `checkforBinary' makes integer from pointer without a cast
http://www.experts-exchange.com/Programming/Programming_Languages/C/Q_20814588.html

project4.c: At top level:
project4.c:123: parse error before `while'
project4.c:126: parse error before `*'
most likely a missing ; or some other punctuation mark ... on line 126 if * is for dereferncing a pointer, make sure that the variable is a pointer indeed

project4.c:126: conflicting types for `addBinary'
project4.c:27: previous declaration of `addBinary'
as error says, you have declared addBinary on line 27 and declared it again on line 126 and both declarations do not match
It is always a good idea to keep your declarations in a header file and #include it

project4.c:126: warning: data definition has no type or storage class
data type not known

project4.c:136: parse error before string constant
project4.c:136: warning: data definition has no type or storage class
project4.c:171: conflicting types for `checkforBinary'
project4.c:30: previous declaration of `checkforBinary'
project4.c:219: conflicting types for `addBinary'
project4.c:126: previous declaration of `addBinary'
project4.c: In function `addBinary':
project4.c:231: warning: passing arg 1 of `strlen' makes pointer from integer without a cast
project4.c:234: warning: passing arg 1 of `strlen' makes pointer from integer without a cast
http://www.experts-exchange.com/Programming/Programming_Languages/C/Q_20814588.html

All remaining errors are similar ...

 

by: buckeyes33Posted on 2003-12-03 at 17:26:37ID: 9871473

Sunny I am going to email you agian and send the code again.  I went through the errors and I was using some bad logic when I was calling functions.  I am going to try to work on int tonight, but I am sick as a dog.  I have at least one logical error, but after I figure that one out i don't know how many I will have.

 

by: sunnycoderPosted on 2003-12-03 at 22:39:31ID: 9872665

buckeyes33,

I went through your code ... I am afraid that in its current state, it indeed is a mess ... If I were to remove all errors from it, it would amount to academic dishonesty ... So I can help you by posting your basic errors here (without posting the code)
e.g. line number this, this is the cause of error ...
you remove the errors .... OK ? If you agree, we can cleanup the code and then talk about logic from there onwards.

Another thing, you have mixed data types quite rashly in your code ... I would suggest that you read some book ... Make sure you declare and define functions with same function signatures ... another place where you seemed to have your data types mixed up is pointers.

Post back if this arrangement is acceptable to you and we will start troubleshooting

 

by: buckeyes33Posted on 2003-12-04 at 20:02:06ID: 9879915

I am going to close this out.   the project was due tonight.  I had fixed all the errors the did not compile.  However, I still had some problems with it.  Oh well.  
for the extra help Sunnycoder I am going to create points for you.

 

by: buckeyes33Posted on 2003-12-04 at 20:04:24ID: 9879925

FYI:  I got part two correct, with your guys help.  Part 1 was were a screwed up.  Getting sick yesterday did not help b/c I lost valuable time that I was praying to the porceline god rather than figuring my mistakes out.

 

by: buckeyes33Posted on 2003-12-04 at 20:07:05ID: 9879937

 

by: buckeyes33Posted on 2003-12-04 at 20:07:19ID: 9879939

once again thanks for the help.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...