Last active
January 21, 2022 08:45
-
-
Save gpc91/4ab473a8acde19b3c5e124904343aee1 to your computer and use it in GitHub Desktop.
Convert a Numerical Type to a binary string and pad it properly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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