ADVERTISEMENT
ADVERTISEMENT

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

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.

Program:

// 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.

Program:

// 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

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.