Ints have 32 bits. We want to see which ones are turned on. We want to see the sign bit. A simple method can be used to display bits.
The binary representation method here has some performance improvements and a simpler calling pattern. Meanwhile Convert.ToString
with PadLeft
is the shortest solution.
Here we look a method that can display bits as zeros and ones from an integer. Every 32-bit integer can be converted into a text display of 32 zeros and ones with this method.
short
as possible, but it helps illustrate how to print bits.toBase
2 example for a shorter (and easier to maintain) implementation.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); } }00000000000000000000000001100100 00000000000000011000011010100000
toBase
Consider this implementation of GetIntBinaryString
. We use Convert.ToString
and specify the toBase
argument as 2. A binary representation is base 2.
PadLeft
to ensure the string
has 32 chars total, with padding added to the left (the start).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'); } }00000000000000000000000001100100 00000000000000011000011010100000
TrimStart
exampleThis method calls TrimStart
. It provides output identical to the JavaScript tool. I haven't found this method as useful, because usually the trailing zeros are useful.
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'); }
We displayed 1s and 0s from an integer, using the C# language. This sort of debugging code can solve hard problems when you are working on complicated structures.