#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

Advertisement

#56 – How to Round When Converting Float to Int

When converting from float or double to int, we cannot use an implicit cast, because data would be lost.  We need an explicit cast, as shown below.  When casting from float or double to int, the resulting value is truncated (rounded towards 0) to get an integral result.

 float f1 = 4.8f;
 //int n1 = f1;        // Compile-time error: cannot implicitly convert
 int n1 = (int)f1;     // Explicit cast, truncated, n1 = 4

If you want to round to the nearest integer, rather than truncating, you can use one of the methods in System.Convert.

 n1 = Convert.ToInt32(4.8f);   // Rounded, n1 = 5

The Convert method always rounds to the nearest integer, unless the result is halfway between two integers.  In this case, it rounds to the nearest even integer.

 n1 = Convert.ToInt32(8.5f);  // Rounded to nearest even, n1 = 8
 n1 = Convert.ToInt32(9.5f);  // Rounded to nearest even, n1 = 10