Ad space (banner)
๐ŸนGo Lessons
Lesson 62 / 68

Converting Number Bases (Binary, Hex)

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

strconv.FormatInt(value, base) converts a number into a string in the base you specify. Going the other way, strconv.ParseInt(text, base, bitSize) turns a string in that base back into a decimal number.

The sample code converts 42 into binary with strconv.FormatInt(int64(num), 2) and into hexadecimal with strconv.FormatInt(int64(num), 16), then converts the binary string back with strconv.ParseInt("101010", 2, 64).

A common stumbling block for beginners is converting between int and int64. FormatInt takes an int64, so an explicit conversion such as int64(num) is required.

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 FormatInt call.

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

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