Integer to binary string in c#

Python has the terribly useful functionality of bin() to do this, but what about C#?

On the rare occasion I have to monkey around with bitwise operators, I always keep this handy. It has the added bonus of printing the leading zeros – I find this very useful when writing/debugging bitwise code, as it makes it easy to line up bitmasks etc. in the immediate window / console.

public static class BinaryPrinter
    public static string ToBinaryString(long _long)
        // have to do this or it won’t print the leading 0 values       
        return Convert.ToString(_long, 2).PadLeft(sizeof(long) * 8, ‘0’); 

Similarly, you could write a few of these (for all of the various inbuilt types) and chuck them in extension methods.

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">