Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
C# BitConverter Static Class
public static class ByteToNumberConversion
{
/// <summary>
/// Converts a specified byte position within the value array into a boolean value.
/// </summary>
[SecuritySafeCritical]
public static bool ToBoolean(this byte[] value, int startIndex = 0)
{
return value[startIndex] != 0;
}
/// <summary>
/// Converts two bytes at a specified position in a byte array into a Unicode character.
/// </summary>
[SecuritySafeCritical]
public static char ToChar(this byte[] value, int startIndex = 0)
{
return (char)ToInt16(value, startIndex);
}
/// <summary>
/// Converts two bytes at a specified position in a byte array into a 16 bit signed integer.
/// </summary>
[SecuritySafeCritical]
public static short ToInt16(this byte[] value, int startIndex = 0)
{
return BitConverter.ToInt16(value, startIndex);
}
/// <summary>
/// Converts two bytes at a specified position in a byte array into a 16 bit unsigned integer.
/// </summary>
[SecuritySafeCritical]
public static ushort ToUInt16(this byte[] value, int startIndex = 0)
{
return (ushort)ToInt16(value, startIndex);
}
/// <summary>
/// Converts two bytes at a specified position in a byte array into a 32 bit signed integer.
/// </summary>
[SecuritySafeCritical]
public static unsafe int ToInt32(this byte[] value, int startIndex = 0)
{
return BitConverter.ToInt32(value, startIndex);
}
/// <summary>
/// Converts two bytes at a specified position in a byte array into a 32 bit unsigned integer.
/// </summary>
[SecuritySafeCritical]
public static uint ToUInt32(this byte[] value, int startIndex = 0)
{
return (uint)ToInt32(value, startIndex);
}
/// <summary>
/// Converts two bytes at a specified position in a byte array into a 64 bit signed integer.
/// </summary>
[SecuritySafeCritical]
public static unsafe long ToInt64(this byte[] value, int startIndex = 0)
{
return BitConverter.ToInt64(value, startIndex);
}
/// <summary>
/// Converts two bytes at a specified position in a byte array into a 64 bit unsigned integer.
/// </summary>
[SecuritySafeCritical]
public static ulong ToUInt64(this byte[] value, int startIndex = 0)
{
return (ulong)ToInt64(value, startIndex);
}
/// <summary>
/// Converts two bytes at a specified position in a byte array into a floating point number.
/// </summary>
[SecuritySafeCritical]
public static float ToFloat(this byte[] value, int startIndex = 0)
{
return BitConverter.ToSingle(value, startIndex);
}
/// <summary>
/// Converts two bytes at a specified position in a byte array into a double precision floating point number.
/// </summary>
[SecuritySafeCritical]
public static double ToDouble(this byte[] value, int startIndex = 0)
{
return BitConverter.ToDouble(value, startIndex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment