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);
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);
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