Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Guys, please i try to Convert a float number to binary but i have a wall bevor me and i need some explanation and help from u. Please don't take care of my language, i'm from Germany. i take the explanation of weekipedia in this "IEEE 754".



hier ist waht i try to do:

C#
public class Float_Prezision
   {
       // deklaration der Privaten member
       private int _bias;               //

       public const int konstante = 127;
       ArrayList value = new ArrayList();
       ArrayList biasbinaere = new ArrayList();

       /** Berechnung der Exponent**/
       public void exponent(float werte)
       {
           if (werte < 0)
               werte -= werte;
           int ganzzahl = Convert.ToInt32(Math.Truncate(Math.Log(werte,2)));
           _bias = ganzzahl + konstante;
           string biaswert = Convert.ToString(_bias,2);
           biasbinaere.Add(biaswert);
           Console.Write(" {0} ",biasbinaere[0]);
       }

       //Methode zur Berechnung der Mantisse
        public void mantisse(float werte)
       {
           int ganzzahlteil = (int)werte;
           Single kommawert = werte - ganzzahlteil;

           int ganzzahlwert;

           for (int i = 0; i < 23; i++)
           {
               Single ergebnis = kommawert * 2;
               ganzzahlwert = (int)ergebnis;
               value.Add(ganzzahlwert);
               kommawert = ergebnis - ganzzahlwert;
               Console.Write("{0}", value[i]);
           }
           Console.WriteLine();
       }
             // Look a sign
       public void vorzeichen(float werte)
       {
           if (werte > 0)
               Console.Write("0");
           else
               Console.Write("1");
       }


      //made a calculation
       public void berechnung(float werte)
       {

           vorzeichen(werte);
           exponent(werte);
           mantisse(werte);
       }


when i compile for example when i give a number 18,4
the result is
010000011 01100110011001100110000
bit i need to have
010000011 00100110011001100110011
please can u help me?
thx Stefan
Posted
Updated 25-Oct-12 12:10pm
v2
Comments
Sergey Alexandrovich Kryukov 25-Oct-12 18:38pm    
No need to look much at your code, because you are not actually looking at bits of the value. You need to use shift and binary & operators to access bits, nothing else.
--SA

Float is already binary, period.

Everything is binary, but your result is "much less binary", because what you right into console is a string or a chain of characters, a human-readable representation of the binary. Let's assume this is what you really need, by some reason. It's still binary in that sense that your '1' or '0' characters are represented in memory as Unicode code points represented as 16-bit UTF-16LE words: 0x30 and 0x31.

The bits of any data type of the size no more then the size of of System.Int32 can be found in this simplified way. Something like this:
C#
static string ToBinaryString(float value) {

    int bitCount = sizeof(float) * 8; // never rely on your knowledge of the size
    char[] result = new char[bitCount]; // better not use string, to avoid ineffective string concatenation repeated in a loop

    // now, most important thing: (int)value would be "semantic" cast of the same
    // mathematical value (with possible rounding), something we don't want; so:
    int intValue = System.BitConverter.ToInt32(BitConverter.GetBytes(value), 0);

    for (int bit = 0; bit < bitCount; ++bit) {
        int maskedValue = intValue & (1 << bit); // this is how shift and mask is done.
        if (maskedValue > 0)
            maskedValue = 1;
        // at this point, masked value is either int 0 or 1
        result[bitCount - bit - 1] = maskedValue.ToString()[0]; // bits go right-to-left in usual Western Arabic-based notation
    }

    return new string(result); // string from character array
}


If the case of arbitrary-size data, you need to serialize to bytes using System.BitConverter and work with individual bytes, in two nested loops.

See also: http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx[^].

To see where are mantissa, exponent, etc., please see: http://en.wikipedia.org/wiki/IEEE_floating_point[^].

Learn the basics.

Good luck,
—SA
 
Share this answer
 
v11
Comments
stefan from germany 25-Oct-12 19:04pm    
Thank you Sergey. i realy don't think about the size. And thx for the link it explain better. I'm a new biginer in c# since 6 Month or 7.
have a nice day.
Stefan
Sergey Alexandrovich Kryukov 25-Oct-12 19:08pm    
You are very welcome.
Good luck, call again.
--SA
CPallini 26-Oct-12 1:47am    
5.
Sergey Alexandrovich Kryukov 26-Oct-12 11:18am    
Thank you, Carlo.
--SA
You forgot to include the integer part (e.g. 18) inside the mantissa.
That is, of the Wikipedia recipe:
Here we can show how to convert a base 10 real number into an IEEE 754 binary32 format using the following outline :
consider a real number with an integer and a fraction part such as 12.375
  1. convert and normalize the integer part into binary
  2. convert the fraction part using the following technique as shown here
  3. add the two results and adjust them to produce a proper final conversion


you missed step 1.

I changed the mantisse method to include such part (just as proof: you may find a way more 'in tune' with your programming style).
//Methode zur Berechnung der Mantisse
    public void mantisse(float werte)
    {
      int ganzzahlteil = (int)werte;
      Single kommawert = werte - ganzzahlteil;

      int norm = 1;
      int mask = 1;
      int ganzzahlteil_copy = ganzzahlteil;
      while ((ganzzahlteil_copy >>= 1 ) > 1)
      {
        norm++;
        mask <<= 1;
      }
      for(int i=0; i<norm;i ++)
      {
        value.Add (((ganzzahlteil & mask) == mask ) ? 1 : 0);
         ganzzahlteil <<= 1;
        Console.Write("{0}", value[i]);
      }

      int ganzzahlwert;

      for (int i = norm; i < 23; i++)
      {
        Single ergebnis = kommawert * 2;
        ganzzahlwert = (int)ergebnis;
        value.Add(ganzzahlwert);
        kommawert = ergebnis - ganzzahlwert;
        Console.Write("{0}", value[i]);
      }
      Console.WriteLine();
    }
 
Share this answer
 
Comments
stefan from germany 25-Oct-12 19:35pm    
Thx CPallini and Sergey. With ur help i understand now realy and show me another initiative. U help me so much. one more time thx guys.
Stefan
CPallini 26-Oct-12 1:48am    
You are welcome.
Sergey Alexandrovich Kryukov 25-Oct-12 21:40pm    
5ed.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900