Skip to content

nterry/Type2Byte

Repository files navigation

Type2Byte (This library is now DEPRECATED and will NO LONGER be maintained)

Build status    NuGet version

A class for converting managed integral types to byte arrays and vice versa

###But BitConverter already exists! Why use this?

A good question. BitConverter is a great class, but only works with the Microsoft CLR. it does not work with Mono. This has now been confirmed incorrect. This library is now DEPRECATED.

###But Mono has DataConvert. Couldn't I just check the platform and use the appropriate lib?

To quote the guys at Xamarin (the developers and maintainers of Mono): Having code that depends on the underlying runtime is considered to be bad coding style, but sometimes such code is necessary to work around runtime bugs...

Indeed, It is bad practice to have platform-specific code and should be avoided wherever possible. This library works with both Mono and the CLR.

In addition, it should be noted that Mono.DataConvert uses unsafe code. If you use a library that is marked with unsafe code your whole project has to marked as such, and you lose all guarantees that the runtime affords to you. You might as well code it in C at this point...

Besides, do you really want to have more than one dependency for the same thing?

###Ok, sold, But how do I use it?

Good choice! Usage is extremely simple:

using Type2Byte.BaseConverters;

class Foo
{
	public void DoSomething()
	{
		//Lets convert some valuetypes to arrays
		long l = T2B.ToBytes(aLong);
		char c = T2B.ToBytes(aChar);
		

		//Lets get some valuetypes from their arrays
		short s = B2T.Get<short>(aByteArray, someOffset);  //The offset is an optional
			int i = B2T.Get<int>(anotherByteArray);	   //parameter and defaults to zero
	}
}

And thats it! All integral types and floating-point types are supported.

Just as a convenience, this library also supports strings as they are extremely common. This is the only referece type that is supported. Use a serializer such as James Newton-King's Json.NET if you need to serialize reference types.

About

A class for converting managed base types to byte arrays and vice versa

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published