C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: This implementation is not as short as possible, but it helps illustrate how to print bits.
Note 2: Please see the Convert toBase 2 example for a shorter (and easier to maintain) implementation.
AndShiftC# program that shows binary representation
using System;
class Program
{
static void Main()
{
// Write full binary string for 100.
Console.WriteLine(GetIntBinaryString(100));
// Write full binary string for 100000.
Console.WriteLine(GetIntBinaryString(100000));
}
static string GetIntBinaryString(int n)
{
char[] b = new char[32];
int pos = 31;
int i = 0;
while (i < 32)
{
if ((n & (1 << i)) != 0)
{
b[pos] = '1';
}
else
{
b[pos] = '0';
}
pos--;
i++;
}
return new string(b);
}
}
Output
00000000000000000000000001100100
00000000000000011000011010100000
Results: The output appears to be correct. To test, I used an online tool from the City University of New York.
Decimal, Binary Conversion Tool: cuny.eduAlso: We use PadLeft to ensure the string has 32 chars total, with padding added to the left (the start).
C# program that uses Convert.ToString, base 2
using System;
class Program
{
static void Main()
{
Console.WriteLine(GetIntBinaryString(100));
Console.WriteLine(GetIntBinaryString(100000));
}
static string GetIntBinaryString(int value)
{
// Use Convert class and PadLeft.
return Convert.ToString(value, 2).PadLeft(32, '0');
}
}
Output
00000000000000000000000001100100
00000000000000011000011010100000
Method that uses TrimStart: C#
static string GetIntBinaryStringRemoveZeros(int n)
{
char[] b = new char[32];
int pos = 31;
int i = 0;
while (i < 32)
{
if ((n & (1 << i)) != 0)
{
b[pos] = '1';
}
else
{
b[pos] = '0';
}
pos--;
i++;
}
return new string(b).TrimStart('0');
}
Note: Thanks to Markus Burrer for providing the Convert.ToString with toBase 2. This is a simpler solution.