I can use Convert.ToString to convert an integer to its binary representation:
int x = 10;
string value = Convert.ToString(x, 2);
Console.WriteLine(value);
I get 1100.
It can even handle negative numbers, as I get 111...0110 (32 bits).
int x = -10;
string value = Convert.ToString(x, 2);
Console.WriteLine(value);
How can I extend this function so that I can give third parameter to get the result with bit filled with 0 (positive value) or 1 (negative value)?
For example, with Convert.ToString(10, 2, 5) –> 01100, and Convert.ToString(-10, 2, 5) –> 10110.
I’ll write my own extension:
call it as :
Also there is no need to pass sign just for convention (with question) I pass it.