除了使用strconv.ParseInt()和strconv.FormatInt()来进行进制间的转换,我们还可以尝试通过数学运算来自己实现
package convert import ( "fmt" "log" "math" "strconv" "strings" ) // Decimal to binary func DecBin(n int64) string { if n < 0 { log.Println("Decimal to binary error: the argument must be greater than zero.") return "" } if n == 0 { return "0" } s := "" for q := n; q > 0; q = q / 2 { m := q % 2 s = fmt.Sprintf("%v%v", m, s) } return s } // Decimal to octal func DecOct(d int64) int64 { if d == 0 { return 0 } if d < 0 { log.Println("Decimal to octal error: the argument must be greater than zero.") return -1 } s :=