Skip to content

Instantly share code, notes, and snippets.

@gpc91
Last active January 21, 2022 08:45
Show Gist options
  • Save gpc91/4ab473a8acde19b3c5e124904343aee1 to your computer and use it in GitHub Desktop.
Save gpc91/4ab473a8acde19b3c5e124904343aee1 to your computer and use it in GitHub Desktop.
Convert a Numerical Type to a binary string and pad it properly.
string NumberToBinary<T>(T val) where T : notnull, IConvertible
{
try
{
long value = val.ToInt64(null);
int size = System.Runtime.InteropServices.Marshal.SizeOf(default(T));
return BitConverter.IsLittleEndian ?
Convert.ToString(value, 2).PadLeft(size * 8, '0') :
Convert.ToString(value, 2).PadRight(size * 8, '0');
}
catch (InvalidCastException e)
{
// Handle exception however you want.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment