In C++, you can serialize your data so easily by simply reading raw bytes of a struct or variable (cast base address of any variable to (unsigned char*) and you can see that variable as its underlying set of bytes that it is.)
But in C#, that ain’t so.
So in C#, you have two options when it comes to seeing the true colors of your variables.
using System;
using System.Runtime.Serialization ;
using System.IO;
public class TestBinaryOutputProgram
{
static void Main()
{
// Using the BitConverter to get raw bytes of
// any PRIMITIVE (doesn't work on a class or a struct
// directly - would have to do member by member manually).
float floatVar = 7.0f;
byte[] fBytes = BitConverter.GetBytes( floatVar ) ;
for( int i = 0; i < fBytes.Length; i++ )
{
Console.WriteLine( "Byte["+i+"] = "+fBytes[i] ) ;
}
// using a MemoryStream
// (or some other stream object)
// and a BinaryWriter
MemoryStream memstream = new MemoryStream();
BinaryWriter bw = new BinaryWriter( memstream ) ;
// write in the var
bw.Write( floatVar ) ; // converts to binary automatically
byte[] memBytes = memstream.ToArray() ;
for( int i = 0; i < memBytes.Length; i++ )
{
Console.WriteLine( "memBytes[" + i + "] = " + memBytes[ i ] );
}
}
}