How can I convert from int to hex

前端 未结 6 2024
你的背包
你的背包 2020-12-14 15:53

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?

6条回答
  •  伪装坚强ぢ
    2020-12-14 16:24

    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

提交回复
热议问题