• Home
  • Blog
  • Demos
  • About
  • ------------------
  • Articles
  • Csharp(59)
    • controls (4)
    • methods (5)
    • tutorials (50)
  • Html(1)
    • tutorials (1)
  • Java(10)
    • mobile (10)
  • Javascript(5)
    • tutorials (5)
  • Linux(3)
    • tutorial (3)
  • Math(10)
    • tutorials (10)
  • Php(15)
    • functions (1)
    • mysql (6)
    • tutorials (8)
  • Sql(23)
    • tutorials (23)
  • Vba(1)
    • tutorials (1)

Converting Int to Binary in C#

Written: 2010-02-05 06:55:54
Mood: Happy
Subject: programming
I needed to convert an integer into binary today and I tried to find a good way to do it, but failed.
Turns out that this was not as common as I thought and google just wasn't that helpful.

At last I found a way to convert int to binary and so I thought I'd share it with you:

string binary = Convert.ToString(4, 2);
//binary = "100"



Now binary holds "100" instead. That's great. What we do here is that we change the base from 10 to 2 (decimal to binary).
If you would like to convert it the other way, binary to int, this is how you would do it:

int dec = Convert.ToInt32("0110", 2);
//dec = 6


However, I was looping through 0 to 127 (in order to create a list of ascii letters in, among other things, binary code) and I wanted all my binaries to be in 8-bit, so I had to add this as well:

for (int i = 0;i <=127 ;i++ )
{

string binary = Convert.ToString(i, 2);

if(binary.Length < 8)
{
int shortComming = 8 - binary.Length;
for (int j = 0;j < shortComming ;j++ )
{
binary = "0" + binary;
}
}
}


As we can see, we add zeroes if the number doesn't have all of them.

That's all =D