Author Topic: [c#] Save float as long, read long and convert back to float  (Read 6239 times)

0 Members and 1 Guest are viewing this topic.

Offline va!n

  • Pentium
  • *****
  • Posts: 1435
  • Karma: 109
    • View Profile
    • http://www.secretly.de
For my actually project i need to store int32 and float values into an int32 array! While some researching and reading on web about the float format, i have tried to code a small piece of code as example how it can be done.

For positive float values it works well... But there is something wrong, when it comes to negative float values... I know i have to do something with the variable called s which stay for signed! 0 == positive number.... 1 == negative number. Atm i am not really sure how but i will try to fix this small bug and i will try to how to do the full way backwards (also writing a float as int32)

I have tried to check if v is not 0, then result-(result*2)... But maybe i just need a small break to think again about it and to solve the problem ^^

However here is my peace of code in C#...

Code: [Select]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

// Small test to read a saved float value as long and convert the long value back to
// the save float value! So you can save float values even in int arrays and just
// need to convert the int back to the original float.
//
// Researched on web for infos about float format and tried to code this small piece of code
//
// Coded by Thorsten Will ('Mr.Vain of Secretly' 01.03.2011)

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // -------- Please define this first !!!

            string filename = @"d:\FloatTest.dat";
            float valueFloat = -3.14f;
            int valueInt32 = 32;

            bool saveValueAsFloat = true;

            // -------- Save float value to a testfile

            if (saveValueAsFloat == true)
            {
                BinaryWriter binWriter = new BinaryWriter(File.Open(filename, FileMode.Create));
                binWriter.Write(valueFloat);
                binWriter.Close();
            }
            else
            {
                BinaryWriter binWriter = new BinaryWriter(File.Open(filename, FileMode.Create));
                binWriter.Write(valueInt32);
                binWriter.Close();
            }

            // -------- Load value as float and as int from testfile

            BinaryReader binReader = new BinaryReader(File.Open(filename, FileMode.Open));
            int value = binReader.ReadInt32();
            binReader.Close();

            // -------- Lets start the magic :)

            //int value = 0x42285375;
            Console.WriteLine("InputValue Long: " + value.ToString() + "    Hex: " + value.ToString("x"));
            Console.WriteLine("----------------");

            int s = (value >> 31);
            Console.WriteLine("v: " + s.ToString());
            int e = (value >> 23);
            Console.WriteLine("e: " + e.ToString());
            int f = (value & 0xffffff);
            Console.WriteLine("f: " + f.ToString());
            Console.WriteLine("----------------");

            e = e - 127;
            Console.WriteLine("e: " + e.ToString());
            float mantise = (1 + (float)(f / Math.Pow(2, 23)));
            Console.WriteLine("mantise: " + mantise.ToString());
            Console.WriteLine("----------------");

            float result = (float)Math.Pow(2, e) * mantise;

            if (s == -1)
            {
                result = -result * 2;
            }


            //if (s) result=-result;

            Console.WriteLine("OutputValue Float: " + result.ToString());

            Console.ReadLine();
        }
    }
}


« Last Edit: March 01, 2011 by va!n »
- hp EliteBook 8540p, 4 GB RAM, Windows 8.1 x64
- Asus P5Q, Intel Q8200, 6 GB DDR2, Radeon 4870, Windows 8.1 x64
http://www.secretly.de
Challenge Trophies Won:

Offline hellfire

  • Sponsor
  • Pentium
  • *******
  • Posts: 1294
  • Karma: 466
    • View Profile
    • my stuff
You got mantissa and exponent working but failed with the sign bit? :)
Code: [Select]
if (s) result=-result;...and there's no static casting in C# ?
Challenge Trophies Won:

Offline va!n

  • Pentium
  • *****
  • Posts: 1435
  • Karma: 109
    • View Profile
    • http://www.secretly.de
No no... i know about the sign bit... 0 == positive and 1 == negative value.... and i have tried to add something like your codeline... but i got always the positive number instead the negative... I am still trying to check it atm... pls wait while trying to solve this problem, maybe i really need a break? XD

[Edited - Added:]
Sorry guys... i will give up now and make a big break for some hours before i look again to the source.
« Last Edit: March 01, 2011 by va!n »
- hp EliteBook 8540p, 4 GB RAM, Windows 8.1 x64
- Asus P5Q, Intel Q8200, 6 GB DDR2, Radeon 4870, Windows 8.1 x64
http://www.secretly.de
Challenge Trophies Won:

Offline Xetick

  • Atari ST
  • ***
  • Posts: 132
  • Karma: 80
    • View Profile
    • Plane9
Could it be that your using signed ints?
Try it with unsiged all the way from the reader (ReadUInt32) to all variables your using.
Plane9 - Home of the Plane9 3d screensaver/music visualizer
Challenge Trophies Won:

Offline Jim

  • Founder Member
  • DBF Aficionado
  • ********
  • Posts: 5301
  • Karma: 402
    • View Profile
Why not use BitConverter.ToSingle()?
http://msdn.microsoft.com/en-us/library/system.bitconverter.tosingle.aspx
It converts an array of 4 bytes to a float.
Code: [Select]
int a = 123456789;
byte [] b = BitConverter.GetBytes(a);
float c = BitConverter.ToSingle(b,0);

Also, why not use xml for your file format?  C# makes that very simple.

Jim
<edit - added code snippet>
« Last Edit: March 01, 2011 by Jim »
Challenge Trophies Won:

Offline va!n

  • Pentium
  • *****
  • Posts: 1435
  • Karma: 109
    • View Profile
    • http://www.secretly.de
@Xetick:
Ups... yes you could be right.. have not checked yet if it works when using uint... (silly small mistake, i thought about uint but used int ^^).

@Jim:
Wow, thanks for the tiny working codesnip! I didnt knew that C# features commands for this! I am amazed everytime again, what C# has all inbuild to makes coders life easier ^^ So many thanks for your info and working code!

@all:
I will try to fix my source! Its nice to see C# has inbuild commands for this... But i would like to know the stuff behind this and how does it works which could be very useful.
- hp EliteBook 8540p, 4 GB RAM, Windows 8.1 x64
- Asus P5Q, Intel Q8200, 6 GB DDR2, Radeon 4870, Windows 8.1 x64
http://www.secretly.de
Challenge Trophies Won: