Question

I ran into this question when watching the twit.tv show coding 101 (episode 2). The code was pre written, but we were asked to change it in order to print out all the values of the while loop that converted an integer to a binary number.

I was able to print out everything with a simple "Console.WriteLine(number);" line. When doing so, it returns all the values for the 32-bit int 0's included.

My question, is there a way to trim or remove all the extra 0's in the division of the loop (not in the final binary number) so they are not printed? Here is the code of the program:

public static string ConvertIntToBinary(int number)
{
    int bits = (sizeof(int) * 16); //32bits
    char[] result = new char[bits]; //Array to hold the binary numbers http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

    while (bits > 0)
    {
        bits = bits - 1;
        int remainder = number % 2; //% called mod or modulo which computes the remainder after dividing http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx

        if (remainder == 1) //If remainder is 1, store it as 1
            result[bits] = '1';
        else
            result[bits] = '0'; //Otherwise store it as 0

        number = number / 2; //Take the original number, divide it by 2
        Console.WriteLine(number);
    }
    return new string(result).TrimStart('0'); //return the result as a string ,removing extra 0's
}
Was it helpful?

Solution

Terminate the loop when number reaches 0. At that point there are no more non-zero bits to pull off:

public static string ConvertIntToBinary(uint value)
{
    int totalbits = sizeof(int) * 8;
    char[] result = new char[totalbits];
    int bits = totalbits;
    uint number = value;

    while (bits > 0)
    {
        bits--;
        uint remainder = number % 2;
        result[bits] = remainder == 0 ? '0' : '1';
        number /= 2;
        if (number == 0)
            break;
    }
    return new string(result, bits, totalbits - bits);
}

I fixed an error in the code: there are 8 bits in a byte, and not 16 as per your code. I also simplified a few parts of the code. I used a conditional expression which is more concise than the if. And I introduced another local variable to hold the working value to avoid modifying the actual parameter. This is generally good practise that makes debugging easier. I also used uint for the input parameter since the entire approach depends on the value being positive.

Note that the termination is inside the loop rather than in the while test. If you test for number equal to 0 in the while condition then you will end up returning the empty string for an input of 0.

OTHER TIPS

Just ignore all the Zero bits as you loop until you hit a '1' bit.

This works with negative numbers as well.

    public static string ConvertIntToBinary(int number)
    {
        if (number == 0) return "0";
        var bits = (sizeof(int) * 8); // 8bits per byte
        var sb = new StringBuilder();
        var print = false;
        var mask = (uint)(1 << bits - 1);
        while (bits-->0)
        {
            var bit = (number & mask) == mask;
            if (bit) print = true;
            if (print) sb.Append(bit ? '1' : '0');
            mask = mask >> 1;
        }
        return sb.ToString();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top