Solved

# converting binary to decimal

Posted on 2003-11-28
66,724 Views
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.
0
Question by:buckeyes33
• 16
• 8
• 6
• +2

LVL 24

Expert Comment

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.
0

LVL 24

Expert Comment

0

LVL 45

Accepted Solution

Kdo earned 500 total points
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
0

LVL 45

Expert Comment

>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
multiply weight by 2
right shift number by one bit
done
your equivalent decimal is in cumulaive sum

Cheers!
Sunny
0

LVL 45

Expert Comment

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
0

LVL 9

Author Comment

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.
0

LVL 45

Expert Comment

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
0

LVL 9

Author Comment

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
0

LVL 45

Expert Comment

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
0

LVL 3

Expert Comment

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.
0

LVL 45

Expert Comment

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

Kent
0

LVL 9

Author Comment

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.
0

LVL 3

Expert Comment

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.

0

LVL 3

Expert Comment

...assuming you are still using a loop.
0

LVL 45

Expert Comment

>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
0

LVL 9

Author Comment

>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.
0

LVL 45

Expert Comment

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
0

LVL 9

Author Comment

>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.
0

LVL 45

Expert Comment

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 );
0

LVL 9

Author Comment

>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);
}
0

LVL 9

Author Comment

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.
0

LVL 45

Expert Comment

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;
}

0

LVL 9

Author Comment

>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.
0

LVL 9

Author Comment

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

LVL 45

Expert Comment

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);
}
0

LVL 9

Author Comment

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");
}

0

LVL 9

Author Comment

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.
0

LVL 45

Expert Comment

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
0

LVL 45

Expert Comment

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

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: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 ...
0

LVL 9

Author Comment

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.
0

LVL 45

Expert Comment

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
0

LVL 9

Author Comment

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.
0

LVL 9

Author Comment

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.
0

LVL 9

Author Comment

0

LVL 9

Author Comment

once again thanks for the help.
0

## Featured Post

### Suggested Solutions

Notes 8.5 Archiving Steps and Tips This article covers setting up a Notes archive, and helps understand some of the menu choices making setting up and maintaining a Notes archive file easier.
I previously wrote an article addressing the use of UBCD4WIN and SARDU. All are great, but I have always been an advocate of SARDU. Recently it was suggested that I go back and take a look at Easy2Boot in comparison.
The viewer will learn how to set up a document for the web and print and the recommended PPI for printing.
The viewer will learn how to create multiple layers to apply various filters and how to delete areas from each layerâ€™s filter.