英文:
Convert an int to hex and then pad it with 0's to get a fixed length String
问题
我在尝试将一个int转换为十六进制,并在前面填充0,以获得一个表示该十六进制数的6个字符的字符串,但遇到了一些问题。
到目前为止,我尝试了以下方法:
intNumber := 12
hexNumber := strconv.FormatInt(intNumber, 16) //不起作用
然后我发现可以使用%06d, number/string来填充0,使所有字符串都变为6个字符长。
在这里你可以找到一个Playground,我设置了一些测试。
有什么高效的方法可以实现这个目标吗?
如果对问题有任何疑问,请在下方留言。
提前感谢。
英文:
I'm having some issues on trying to convert an int to hex then, padding it with 0s in order to get a 6 Characters String which represents the hex number.
So far, I tried the following:
intNumber := 12
hexNumber := strconv.FormatInt(intNumber, 16) //not working
And then I found out how to pad it with 0s, using %06d, number/string. It makes all the strings 6 characters long.
Here you can Find a Playground which I set up to make some tests.
How can I achieve this in a efficient way?
For any Clarifications on the question, just leave a comment below.
Thanks In advance.
答案1
得分: 20
import "fmt"
hex := fmt.Sprintf("%06x", num)
x 表示十六进制,6 表示6位数字,0 表示左侧用零填充,% 开始整个序列。
英文:
import "fmt"
hex := fmt.Sprintf("%06x", num)
The x means hexadecimal, the 6 means 6 digits, the 0 means left-pad with zeros and the % starts the whole sequence.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论