It looked like that I can print a number in hexadecimal format with
Console.Write, but I couldn't find how to print in binary format. I
mean 000...0001 for 1, 000...0010 for 2 and so on.
I wrote a dirty code, and it seemed to be working, but it looks like
quite inefficient. Is there any .NET built in method or a better way?
Below is the code I wrote:
class Program
{
static void Main(string[] args)
{
PrintInBinary(1);
PrintInBinary(1<<2);
}
static void PrintInBinary(int num)
{
byte[] bytes = BitConverter.GetBytes(num);
for (int count = bytes.Length - 1; count >= 0; count--)
{
for (int position = 7; position >= 0; position--)
PrintBitAt(bytes[count], position);
Console.Write(" ");
}
Console.WriteLine();
}
static void PrintBitAt(byte b, int position)
{
if(position>7)
return;
byte a=(byte)Math.Pow(2,position);
if ((b & a) == a)
Console.Write("1");
else
Console.Write("0");
}
}