How can I convert from int to hex

做~自己de王妃 提交于 2019-12-18 12:12:42

问题


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?


回答1:


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'



回答2:


"Hex" isn't a real thing. You can use a hexadecimal representation of a number, but there's no difference between 0xFF and 255. More info on that can be found in the docs which point out you can use 0xff to define an integer constant 255! As you mention, if you're trying to find the hexadecimal representation of an integer you could use strconv

package main

import (
    "fmt"
    "strconv"
)

func main() {
    fmt.Println(strconv.FormatInt(255, 16))
    // gives "ff"
}

Try it in the playground




回答3:


If formatting some bytes, hex needs a 2 digits representation, with leading 0.

For exemple: 1 => '01', 15 => '0f', etc.

It is possible to force Sprintf to respect this :

h:= fmt.Sprintf("%02x", 14)
fmt.Println(h) // 0e
h2:= fmt.Sprintf("%02x", 231)
fmt.Println(h2) // e7

The pattern "%02x" means:

  • '0' force using zeros
  • '2' set the output size as two charactes
  • 'x' to convert in hexadecimal


来源:https://stackoverflow.com/questions/33581426/how-can-i-convert-from-int-to-hex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!