Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 62 / 68

Converting Number Bases (Binary, Hex)

In this lesson you will learn how to convert between number bases in C#, deepening your understanding of how numbers are represented inside a computer. This is for anyone searching for "C# base conversion how to use".

Convert.ToString(number, base) converts a number into a string in the base you specify. Going the other way, Convert.ToInt32(text, base) turns a string in that base back into a decimal number.

The sample code converts 42 into binary with Convert.ToString(42, 2) and into hexadecimal with Convert.ToString(42, 16), then converts the binary string back with Convert.ToInt32("101010", 2).

A common stumbling block for beginners is the relationship between the base and the actual value. Hexadecimal uses the letters a to f after 0 to 9, so the notation takes some getting used to if you only think in decimal.

Binary is used inside the computer and hexadecimal in colour codes, making this worthwhile background knowledge. Octal works the same way - just change the base argument of the same Convert method.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)