[Solved] c# bit shift task with integers


What does this code do? How would have you named such a function?
I would have named it so

/// <summary>
/// Convert an Int32 value into its binary string representation.
/// </summary>
/// <param name="value">The Int32 to convert.</param>
/// <returns>The binary string representation for an Int32 value.</returns>
public String ConvertInt32ToBinaryString(Int32 value)
{
        String pout = "";    
        int mask = 1 << 31;

        for (int n = 1; n <= 32; n++)
        {
            pout += (value & mask) == 0 ? "0" : "1";
            value <<= 1;
            if (n % 4 == 0)
            {pout += " ";}
        }

        return pout;
}

The question in your exam could be rephrased as “give me binary representation of -99887766 in 32 bit two-complementary code”.

There is no very simple and fast conversion to binary but 10 minutes are quite enough for a value below 10 millions. There are few methods but on paper I usually prefer “Descending Powers of Two and Subtraction” over “Short Division by Two with Remainder” http://www.wikihow.com/Convert-from-Decimal-to-Binary.

Just don’t (already having binary representation in second step) make those bit comparisons with bit mask.

3

solved c# bit shift task with integers