Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 62 / 68

Converting Number Bases (Binary, Hex)

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

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

The sample code converts 42 into binary with num.toString(2) and into hexadecimal with num.toString(16), then converts the binary string back with "101010".toInt(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. For octal, just change the base argument of the same toString call.

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

๐Ÿงช This site can't compile or run Kotlin 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)