Convert Decimal to Hexadecimal in Go
In this tutorial, we will learn how to convert a decimal number to hexadecimal in Go. We will cover the basic concept of hexadecimal numbers and implement a function to perform the conversion.
What is Hexadecimal Conversion
Hexadecimal conversion is the process of converting a decimal (base-10) number to a hexadecimal (base-16) number. In hexadecimal, numbers are represented using digits from 0 to 9 and letters from A to F.
Syntax
The syntax to convert a decimal number to hexadecimal in Go is:
func decimalToHexadecimal(n int) string {
if n == 0 {
return "0"
}
hex := ""
hexDigits := "0123456789ABCDEF"
for n > 0 {
remainder := n % 16
hex = string(hexDigits[remainder]) + hex
n = n / 16
}
return hex
}
Example 1: Converting a decimal number to hexadecimal
We can create a function to convert a given decimal number to hexadecimal by repeatedly dividing the number by 16 and keeping track of the remainders.
For example,
- Define a function named
decimalToHexadecimal
that takes one parametern
of typeint
. - Check if
n
is 0. If true, return '0'. - Initialize an empty string
hex
to store the hexadecimal representation. - Initialize a string
hexDigits
containing the hexadecimal digits from 0 to F. - Use a
for
loop to repeatedly dividen
by 16 and prepend the corresponding character fromhexDigits
tohex
untiln
becomes 0. - Return the hexadecimal representation as a string.
- In the main function, call the
decimalToHexadecimal
function with a sample number and print the result.
Go Program
package main
import (
"fmt"
)
func decimalToHexadecimal(n int) string {
if n == 0 {
return "0"
}
hex := ""
hexDigits := "0123456789ABCDEF"
for n > 0 {
remainder := n % 16
hex = string(hexDigits[remainder]) + hex
n = n / 16
}
return hex
}
func main() {
// Convert 255 to hexadecimal
result := decimalToHexadecimal(255)
// Print the result
fmt.Printf("Hexadecimal representation of 255 is %s\n", result)
}
Output
Hexadecimal representation of 255 is FF