Golang | How can I convert from int to hex?

Golang | Converting from int to hex: Here, we are going to learn how can I convert from int to hex in Go programming language?
Submitted by IncludeHelp, on August 04, 2021

Converting from int to hex in Golang

There are two ways to convert from int to hex,

1) Int to hex conversion using fmt.Sprintf()

In Golang (other languages also), hexadecimal is an integral literal, we can convert hex to int by representing the int in hex (as string representation) using fmt.Sprintf() and %x or %X. %x prints the hexadecimal characters in lowercase and %X prints the hexadecimal characters in uppercase.

Golang code for Int to hex conversion using fmt.Sprintf()

// Golang program for int to hex conversion
// using fmt.Sprintf()

package main

import (
	"fmt"
)

func main() {
	int_value := 123

	hex_value := fmt.Sprintf("%x", int_value)
	fmt.Printf("Hex value of %d is = %s\n", int_value, hex_value)

	hex_value = fmt.Sprintf("%X", int_value)
	fmt.Printf("Hex value of %d is = %s\n", int_value, hex_value)

	int_value = 65535

	hex_value = fmt.Sprintf("%x", int_value)
	fmt.Printf("Hex value of %d is = %s\n", int_value, hex_value)

	hex_value = fmt.Sprintf("%X", int_value)
	fmt.Printf("Hex value of %d is = %s\n", int_value, hex_value)
}

Output:

Hex value of 123 is = 7b
Hex value of 123 is = 7B
Hex value of 65535 is = ffff
Hex value of 65535 is = FFFF

2) Int to hex conversion using strconv.FormatInt()

To convert from int to hex, we can also use strconv.FormatInt() method which is defined in strconv package.

Golang code for Int to hex conversion using strconv.FormatInt()

// Golang program for int to hex conversion
// using strconv.FormatInt()

package main

import (
	"fmt"
	"strconv"
)

func main() {
	int_value := 123

	hex_value := strconv.FormatInt(int64(int_value), 16)
	fmt.Printf("Hex value of %d is = %s\n", int_value, hex_value)

	int_value = 65535

	hex_value = strconv.FormatInt(int64(int_value), 16)
	fmt.Printf("Hex value of %d is = %s\n", int_value, hex_value)
}

Output:

Hex value of 123 is = 7b
Hex value of 65535 is = ffff




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.