Posts

Showing posts from May, 2010

C# BitConverter

Missing the flexibility of C/C++ way in interpreting bits? In C/C++, you can reinterpret the bits by simply casting it. For example if you have an int and you want to reinterpret it as float , you can do the following: int i = 1234; float f = *( (float*) &i ); The question is how can we do this in C#? It turns out there's a class in C# to do this. Meet BitConverter class. int i = 1234; float f = BitConverter.ToSingle( BitConverter.GetBytes(i), 0 ); With this class, you can reinterpret bits from primitive data types. Which should be enough. The only problem is that the class is not suitable to be called every frames. Why? Using Reflector.NET, you can easily tell that BitConverter.GetBytes() is actually allocating memory! public static unsafe byte[] GetBytes(int value) { byte[] buffer = new byte[4]; fixed (byte* numRef = buffer) { *((int*) numRef) = value; } return buffer; } One solution is just to keep in mind not to call this every frame....