Mono.DataConvert

by Miguel de Icaza

Our just released Mono 1.2.4 contains a class that replaces System.BitConverter: Mono.DataConvert.

We created this interface a few months ago when we ran into problems with the limitations in System.BitConverter in Mono and when we noticed that it was not possible to fix this API. Mono is switching internally to use this instead of BitConverter as it leads to subtle errors when making your code work in big-endian systems.

Mono.DataConvert offers conversions from and to .NET types to raw byte sequences:

  • Host types to native byte arrays, little endian byte arrays and big endian byte arrays.
  • native, little endian, big endian to Host types.
  • Helper routines for Stream I/O.
  • Perl-like convenience routines for packing and unpacking data structures.

I like the Perl-like interface, for example:

	// The following means:
	// Little endian encoding of a Int16, followed by an aligned
	// int32 value.
	byte [] r = DataConverter.Pack ("_s!i", 0x7b, 0x12345678);

	DataConverter.Pack ("^ii", 0x1234abcd, 0x7fadb007)
	// Result: 12 34 ab cd 7f ad b0 07
	

We also have a more traditional APIs, for example:

	// The instance-based API
	byte [] x;
	x = DataConverter.LittleEndian.GetBytes (my_double_value);
	x = DataConverter.Host.GetBytes (my_double_value);
	x = DataConverter.BigEndian.GetBytes (my_double_value);

	// Or a static version of it:
	x = DataConverter.GetBytesLE (my_double_val);
	x = DataConverter.GetBytesNative (my_double_val);
	x = DataConverter.GetBytesBE (my_double_val);
	

The code is licensed under the MIT X11 license, and we encourage developers on both Mono and .NET to use this library as opposed to the fundamentally limited and broken BitConverter.

This class is bundled as part of corlib, and is by default "internal". Since this is a small class, developers are encouraged to copy the source code into their own applications. See this for details

Posted on 15 May 2007