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#...
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();
}
}
}