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,

  1. Define a function named decimalToHexadecimal that takes one parameter n of type int.
  2. Check if n is 0. If true, return '0'.
  3. Initialize an empty string hex to store the hexadecimal representation.
  4. Initialize a string hexDigits containing the hexadecimal digits from 0 to F.
  5. Use a for loop to repeatedly divide n by 16 and prepend the corresponding character from hexDigits to hex until n becomes 0.
  6. Return the hexadecimal representation as a string.
  7. 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