Ad space (banner)
๐ŸฆSwift Lessons
Lesson 62 / 68

Converting Number Bases (Binary, Hex)

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

String(value, radix: base) converts a number into a string in the base you specify. Going the other way, Int(text, radix: base) turns a string in that base back into a decimal number.

The sample code converts 42 into binary with String(num, radix: 2) and into hexadecimal with String(num, radix: 16), then converts the binary string back with Int("101010", radix: 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 radix argument to 8.

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

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