我如何在Golang中将int转换为十六进制? [英] How can I convert from int to hex in Golang?

查看:2022
本文介绍了我如何在Golang中将int转换为十六进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Golang中将int从int转换为hex。
在strconv中,有一种将字符串转换为十六进制的方法。是否有类似的方法来从一个int获得十六进制字符串?

由于十六进制是一个 Integer文字,你可以询问 noreferrer> fmt package 获取该整数的字符串表示形式, fmt.Sprintf() 以及%x %X 格式。

参观游乐场

  i:= 255 
h:= fmt.Sprintf(%x,i)
fmt.Printf '是'%s'\\\
,i,h)
h = fmt.Sprintf(%X,i)
fmt.Printf('%d'的HEX转换为'%' s'\\\
,i,h)

输出:

 '255'的十六进制转换为'ff'
'255'的HEX转换为'FF'


I want to convert from int to hex in Golang. In strconv, there is a method that converts strings to hex. Is there a similar method to get a hex string from an int?

解决方案

Since hex is a Integer literal, you can ask the fmt package for a string representation of that integer, using fmt.Sprintf(), and the %x or %X format.
See playground

i := 255
h := fmt.Sprintf("%x", i)
fmt.Printf("Hex conv of '%d' is '%s'\n", i, h)
h = fmt.Sprintf("%X", i)
fmt.Printf("HEX conv of '%d' is '%s'\n", i, h)

Output:

Hex conv of '255' is 'ff'
HEX conv of '255' is 'FF'

这篇关于我如何在Golang中将int转换为十六进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆