#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Thorsten says:

    Hey Sean,

    shoudn’t it be i2 and i3 on the second and third Console.WriteLine call?

    Keep on the good work!

    Cheers

Leave a comment