Skip navigation

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 ] );
    }

  }
}


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: