十进制数转成十六进制【golang】

十进制数字转成十六进制字符串:

package main

import (
	"fmt"
	"strings"
)

func toHex(ten int) string {
	m := 0
	hex := make([]int, 0)
	for {
		m = ten % 16
		ten = ten / 16
		if ten == 0 {
			hex = append(hex, m)
			break
		}
		hex = append(hex, m)
	}
	hexStr := []string{}
	for i:=len(hex)-1;i>=0;i--{
		if hex[i] >= 10 {
			hexStr = append(hexStr, fmt.Sprintf("%c", 'A'+hex[i]-10))
		} else {
			hexStr = append(hexStr, fmt.Sprintf("%d", hex[i]))
		}
	}
	return strings.Join(hexStr, "")
}

func main() {
	msgHex := toHex(16161616)
	fmt.Println(msgHex)
}

运行结果:

GOROOT=D:\Go #gosetup
GOPATH=D:\Go\bin;C:\Users\Y2\go;D:\Golang Projects #gosetup
D:\Go\bin\go.exe build -o C:\Users\Y2\AppData\Local\Temp\___go_build_adfadf_go.exe "D:\Golang Projects\src\diandian\myproject\iuioo\adfadf.go" #gosetup
C:\Users\Y2\AppData\Local\Temp\___go_build_adfadf_go.exe #gosetup
F69B50


你可能感兴趣的:(golang,golang)