Search code examples
c#hexmultiplication

C# multiplying gives wrong answer


when i try to multiply hex values like this

int i = 0x4;
int z = i * 3;

it says z = 12 c# just treats it like a normal number (answer should be C)


Solution

  • An int simply contains an integer value without any base associated with it.

    By default an int is initialized to a decimal:

    int x = 27;
    

    By default an int is displayed as a decimal:

    Console.Write (x); // Shows 27
    

    An int can also be initialized to a binary or a hexadecimal:

    int y = 0xAA;
    int z = 0b0101;
    

    And displayed as them as hexadecimal:

    Console.Write(y.ToString("X")); // Shows AA
    

    But the way it is initialized and the way it is displayed are entirely independent.