Solved

binary to float

Posted on 2003-11-06
14
750 Views
Last Modified: 2013-11-15

I have written a simple program which gets a float binary ( like 110.01 ) and returns
however it does not work where have done wrong?

if I enter 11.10 the porgram give nothing
if I enter 11.01 the program gives 3.00
why does the program stops when it sees a 1 after ' . '
moreover
enterin 100 gives 5 instead of 4
I would like to put a if (binNum%2=0{
sum=sum-1}
does this influence the value of binNum?


#include <stdio.h>

int bin2dec(int binNum) {
      int x;  
        int sum;
        sum=0;  
      x=1;
      
      do {
            sum=sum+x;          
            x*=2;
      } while((binNum/=10)>0);
      
      return sum;
       
}
float bintofloat(float binNum2){
float y;
float summ;
summ=0.0;
y=0.5;

while (binNum2*10.0>1.0){
summ=summ+y;
y*=0.5;
}

return summ;
}

int main()
{
int a;
int sum;
float summ;
float binNum;
float binNum2;
float answer;
scanf("%f",&binNum);
a=(int)binNum;
binNum2=binNum-a;
sum=bin2dec(a);
summ=bintofloat(binNum2);
answer=sum+summ;
printf("%f",answer);
return 0;
}
0
Comment
Question by:hermesc
  • 4
  • 3
  • 3
  • +2
14 Comments
 
LVL 45

Expert Comment

by:Kdo
Comment Utility

Ok.  There seems to be some confusion over what integer, float, decimal, and bin all represent.  The function bin2dec() is a good indication of the problem.

bin2dec() seems to form of log10(x), returning a mask that represents the log10() of the original number.  4 return 1, 21 return 3, 176 returns 7, 4512 returns, 0xF, etc.


In C, all numbers ARE binary, no matter what the type is.  (C doesn't support BCD or packed decimal.)


So what are you trying to accomplish and maybe I can be more help.

Kent
0
 

Author Comment

by:hermesc
Comment Utility
well bintodec part works well and it is not the log of it

assume 100101
i get the remain part 1
x=1
 divide by 10
remainer part 0 x=2 but skips it
divide by 10
remainer part 4 x=4
now I have 5 and it goes on ....


but the other does not ,

In the program I will enter a
number like 101.010 and the output will be
5.25


0
 
LVL 45

Expert Comment

by:Kdo
Comment Utility

Ok.  I still don't know what you're trying to do.

If you look at 101.010 as a decimal floating point number (and it is) then you get 101 as the "integer" part and .010 as the factional part.

101 in binary IS 5 decimal.  010 in binary is 2 decimal.  Put them together and you get 5.2 (The trailing 5 in your answer is something else that has crept into the result.)  Your program splits the integer and fractional parts, treats the decimal integer value as if it were a binary value and converts it back to int.  (A meaningless conversion.)

When you enter 101.010 what do you expect to get for an answer?

Kent
0
 
LVL 16

Expert Comment

by:imladris
Comment Utility
I am, like Kdo, completely in the dark as to what this program is supposed to do.

However, as to the two implied questions at the top:

why does the program give nothing for 11.10?

For 11.10 the variable a is assigned 11, the variable binNum2 gets 11.10-11 = 0.10. So bintofloat is called with an argument of 0.10.

In bintofloat the loop condition is:

while(binNum2*10.0>1.0)

Now calculations are always done in double, and because of the vagueries of floating point arithmetic, binNum2*10.0 winds up being 1.0000038146973; i.e. slight more than 1, and so the loop executes.
The actions inside the loop alter summ and y, but nothing ever alters the value of bigNum2, and so the condition continues to be true, and the loop executes forever. Your program is "hung".

For 11.01, bintodec executes the loop twice.
The argument is 11, sum starts at 0, and x at 1. So in the first iteration sum becomes 1. Then x is multiplied up to 2. binNum/10 is greater than 0 so sum has the new x (2) added to it and becomes 3. Dividing binNum by 10 again leaves it at 0, and the loop exits returning 3.

For bintofloat the loop never executes because 0.01*10.0 is less than 1, so it returns 0.

So, answer becomes 3 + 0 which is 3.


0
 

Author Comment

by:hermesc
Comment Utility
what the program is supposed to do is

getting a number in the format of
1 and 0 s and then convert it to a 10 based number
like this 1.1 -->>1.5
or 101.01-->> 5.25

to imladris : I see the loop error and I am asking how can I overcome the problem
"For bintofloat the loop never executes because 0.01*10.0 is less than 1, so it returns 0.

So, answer becomes 3 + 0 which is 3"

wont the loop continue to multiply by 10 until it gets >1 ?
as the othe loops does?
0
 
LVL 16

Expert Comment

by:imladris
Comment Utility
The loop statement:

while(binNum2*10.0>1.0)

does not alter the value of binNum2, nor do any of the statements in the loop. So it will always evaluate to the same number.

If you want the loop to multiply binNum2 by 10, and continue to do so until it is greater than 1.0 (i.e. you want the loop to end when it becomes greater than 1.0) that is equivalent to say you want it to continue iterating *while* it is less than 1.0. So

while((binNum2*=10.0)<1.0)

should be closer to your requirements.
0
 
LVL 45

Expert Comment

by:Kdo
Comment Utility

Ok.  So the integer portion seems to be working OK.  Let's clean up the fractional part, function bin2float().

float bin2float (float Value)
{
  float NewValue = 0;
  int    Digit;
  float TempValue = .5

  while (Value != 0.0)
  {
    Digit = Value * 10;  /*  Grab the top digit  */
    if (Digit)
      NewValue += TempValue;
    Value -= Digit;            /*  Throw the used digit away  */
    Value = Value * 10;    /*  shift the next digit up  */
    TempValue /= 10.
  }
  return NewValue;
}


If you'll replace your bin2float() function with this one, I think you'll get the result that you're looking for.


Kent

0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 5

Accepted Solution

by:
mtmike earned 500 total points
Comment Utility
This is not really the right way to read in a binary floating point number. The algorithm you are trying to use is extremely instable and will only work for very small binary floats.

Also, if you enter a normal float by accident (eg 33.6) things will go wrong without notice.

It is much easier to read in a binary float character by character and construct the actual floating point number on the fly. Allows you to do some error checking too.

Try something like this:

#include <stdio.h>

int main()
{
      float x, a;
      char ch;

      /* Read in the integral part */
      x = 0;
      ch = getchar();
      while (ch == '0' || ch == '1') {
            x *= 2;
            if (ch == '1') {
                  x += 1;
            }
            ch = getchar();
      }

      if (ch == '.') {

            /* Read in the fraction */
            a = 0.5;
            ch = getchar();
            while (ch == '0' || ch == '1') {
                  if (ch == '1') {
                        x += a;
                  }
                  a /= 2;
                  ch = getchar();
            }
      }

      printf("%f\n", x);
      return 0;
}
0
 

Author Comment

by:hermesc
Comment Utility
ok that works but I dont get the way how does the program recognise the length of numbers I mean
how does the program get that the first entered number is the 2^5 or 2^2
??
0
 
LVL 5

Expert Comment

by:mtmike
Comment Utility
You multiply the value you have seen so far by two whenever you see a new digit. So, when the first number is 2^5 there will be five more digits. When all digits have been seen, you will have multiplied the first digit by two five times.

Some examples...

Input: 100 (binary)

x = 0
x = x*2+1 = 1
x = x*2+0 = 2
x = x*2+0 = 4

Input: 10010 (binary)

x = 0
x = x*2+1 = 1
x = x*2+0 = 2
x = x*2+0 = 4
x = x*2+1 = 9
x = x*2+0 = 18
0
 
LVL 16

Expert Comment

by:imladris
Comment Utility
Assume 101.01 was entered.

1 is added to x.
In both subsequent iterations of the loop, x is doubled. Thus the one that is originally added, is implicitly raised to the 3rd power (2^3) because it is multiplied up as many times as there are digits in the number.
0
 

Author Comment

by:hermesc
Comment Utility
ok I got it this is the way computer thinks
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
int bin2dec(int binNum) {
     int x;  
        int sum;
        sum=0;  
     x=1;
     
     do {
          sum=sum+x*(binNum%10);          
          x*=2;
     } while((binNum/=10)>0);
     
     return sum;
       
}
float bintofloat(float binNum2){
float y;
float summ;
summ=0.0;
y=0.5;

 while( y > 0.001 ){
   binNum2 *= 10;
   summ=summ+y*(int)(binNum2+.5);
y*=0.5;
 binNum2 -= (int)(binNum2+.5);
}

return summ;
}
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
while( y > 0.01 ){ /*unless you're using double */
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Let’s list some of the technologies that enable smooth teleworking. 
The article will include the best Data Recovery Tools along with their Features, Capabilities, and their Download Links. Hope you’ll enjoy it and will choose the one as required by you.
This video demonstrates how to use each tool, their shortcuts, where and when to use them, and how to use the keyboard to improve workflow.
The viewer will learn how to successfully download and install the SARDU utility on Windows 8, without downloading adware.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now