#1,111 – Converting an Integer to a String in a Different Base

You can convert an integer-based value to a string using the ToString method on the integer.  This results in a string representing the integer as a base 10 number.

            int i = 42;
            // ToString() called implicitly
            Console.WriteLine(i);  // base 10

1111-001

You can also convert integer-based values to strings that represent the number in base 2 (binary), 8 (octal), or 16 (hexadecimal).  You use the Convert.ToString method, passing it the number to convert and the base.

            int i = 42;
            int i2 = 1964;
            int i3 = -128;

            Console.WriteLine("{0} dec, {1} hex, {2} oct, {3} bin",
                i,
                Convert.ToString(i, 16),
                Convert.ToString(i, 8),
                Convert.ToString(i, 2));

            Console.WriteLine("{0} dec, {1} hex, {2} oct, {3} bin",
                i2,
                Convert.ToString(i2, 16),
                Convert.ToString(i2, 8),
                Convert.ToString(i2, 2));

            Console.WriteLine("{0} dec, {1} hex, {2} oct, {3} bin",
                i3,
                Convert.ToString(i3, 16),
                Convert.ToString(i3, 8),
                Convert.ToString(i3, 2));

1111-002

#57 – Overflow on Integer Operations

When executing arithmetic operations on integer-based types, an overflow can occur when the result of the operation cannot be stored in the destination type.

By default in C#.NET, when overflow occurs for integer-based types, the most significant bits of the result are discarded.  Effectively, this results in the value appearing to wrap.  E.g. Large values wrap to smaller (or large negative for unsigned) values.

Here are some examples of wrapping on integer-based overflow.

 uint u1 = 0xffffffff;
 u1 = u1 + 5;       // Now 0x00000004 (wrapped)

 int n1 = int.MaxValue;      // 2147483647 (0x7FFFFFFF)
 n1 = n1 + 1;                // Now -2147483648 (wrapped)

 short s1 = short.MinValue;
 s1 = (short)(s1 - 1);       // Now 32767 (wrapped)