#1,111 – Converting an Integer to a String in a Different Base
June 5, 2014 2 Comments
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
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));