none
Why does 0x5 converts to 101 with Convert.ToString? And, in "Convert.ToString(0x5 ^ 0x3, 2));" what does the ",2" do? RRS feed

  • Question

  • Reference: http://msdn.microsoft.com/en-us/library/zkacc7k1.aspx

    In the above website, there is the following passage which has confused me: 

    // Bitwise exclusive-OR of 101 (5) and 011 (3) returns 110 (6).
    Console.WriteLine("Bitwise result: {0}", Convert.ToString(0x5 ^ 0x3, 2));

    Could someone please help me by explaining:

    Q1: Shouldn't "0x5" to converted to 5? Why is it converted to 101? (Is there an Msdn page on hexadecimal conversion?)

    Q2: What does the", 2" do?

    Much thanks!!





    Wednesday, October 1, 2014 3:09 PM

Answers

  • The 101 for 5, 011 for 3, and 110 for 6 are the binary representation of the numbers. The reason why they are included in the comments is that the code is doing a bitwise operation, that is it is operating on the binary digits of the numbers.

    The Exclusive Or operator (^ in c#) will set each bit in the result equal to 1 if the equivalent bit on one (but not both) of the two inputs is 1, and will set it to 0 is the equivalent bits in the two inputs are both 1 or both 0.

    The example works like this:

    101 XOr
    011
    ---
    110

    The left hand bit is 1 in the first input and 0 in the second, so it is 1 in the result.
    The middle bit is 0 in the first input and 1 in the second, so it is 1 in the result.
    The right hand bit is 1 in both inputs, so it is 0 in the result.

    The result is 110 which is binary for 6.

    The answer to your second question is that the ", 2" in the Convert.ToString arguments is to say that the number should be displayed in base 2 (that is binary).
    • Edited by Blackwood Wednesday, October 1, 2014 4:10 PM Add second answer
    • Marked as answer by KommSusserTod Thursday, October 2, 2014 2:57 AM
    • Unmarked as answer by KommSusserTod Thursday, October 2, 2014 2:57 AM
    • Marked as answer by KommSusserTod Thursday, October 2, 2014 2:58 AM
    Wednesday, October 1, 2014 3:30 PM