Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define Human_Readable
- // Comment-out the line above to do binary serialization instead. Both work.
- using System;
- using System.IO;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Xml.Serialization;
- namespace FloatSerializationTest
- {
- class Program
- {
- static void Main(string[] args)
- {
- Random random = new Random();
- int sampleCount = 10000;
- // Generate a big array of random floats between 0 and 1:
- float[] originalValues = new float[sampleCount];
- for (int i = 0; i < sampleCount; i++)
- originalValues[i] = (float)random.NextDouble();
- // Save the floats to a file.
- SaveFloatArray(originalValues);
- // Load the floats back from the file.
- float[] loadedValues = LoadFloatArray();
- for(int i = 0; i < sampleCount; i++)
- {
- double error = (double)originalValues[i] - (double)loadedValues[i];
- Console.WriteLine(originalValues[i] + ": " + error);
- if(error != 0.0)
- {
- Console.WriteLine("Dearest Krythic, you were correct, please accept my apology.");
- // Note: sadly, the preceding line never runs. ;)
- Console.ReadLine();
- return;
- }
- }
- // This line runs instead.
- Console.WriteLine("All values are exactly equal after saving to a file & reading them back.");
- Console.ReadLine();
- }
- static void SaveFloatArray(float[] data)
- {
- FileStream fs = new FileStream("savedFloats.dat", FileMode.Create);
- // Choose binary or human-readable text - both work just fine!
- #if Human_Readable
- var formatter = new XmlSerializer(typeof(float[]));
- #else
- var formatter = new BinaryFormatter();
- #endif
- try
- {
- formatter.Serialize(fs, data);
- }
- catch (SerializationException e)
- {
- Console.WriteLine("Failed to serialize. Reason: " + e.Message);
- throw;
- }
- finally
- {
- fs.Close();
- }
- }
- static float[] LoadFloatArray()
- {
- float[] data;
- FileStream fs = new FileStream("savedFloats.dat", FileMode.Open);
- #if Human_Readable
- var formatter = new XmlSerializer(typeof(float[]));
- #else
- var formatter = new BinaryFormatter();
- #endif
- try
- {
- data = (float[])formatter.Deserialize(fs);
- }
- catch (SerializationException e)
- {
- Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
- throw;
- }
- finally
- {
- fs.Close();
- }
- return data;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement