Wednesday, June 30, 2010

Conversion from decimal to binary

Psuedo Code:

do
{
    bin = ((dec % 2 == 0) ? "0" : "1") + bin;
    dec /= 2;
} while (dec != 0);


C# Syntax:

private string DecToBin(long dec)
{
    string bin = string.Empty;
    string zero = "0";
    string one = "1";
    do
    {
            bin = string.Format("{0}{1}", ((dec % 2 == 0) ? zero : one), bin);
            dec /= 2;
    } while (dec != 0);

    return bin;
}

No comments: