views:

212

answers:

5

In C#, how can I output a number as binary to the console? For example, if I have a uint with the value of 20, how can I print to the console: 00010100 (which is 20 in binary)?

+8  A: 

Convert.ToString (myValue, 2);

Petoj
+2  A: 
int x = 3;
string binaryString = Convert.ToString(x, 2);
Console.WriteLine(binaryString);

Console will display 11.

Brownie
+1  A: 
Console.WriteLine(Convert.ToString(20, 2));
marshall
+3  A: 

With padding to make the value a byte:

Console.WriteLine(Convert.ToString(number, 2).PadLeft(8, '0'));
Cameron MacFarland
A: 

Thank You. I have been looking into how to format an output string into binary. It seems like an absurdly simply task; however, C# makes things so easy sometimes I forget good old brute force console formatting. This was very helpful and better than my way.