Base Conversion 2
/* * Take two numbers from the command line and print the fist one * in the base given by the second. */ package main import ( "fmt" "os" ) func main() { // Declare two integers variables. var num, base int fmt.Sscan(os.Args[1], &num) fmt.Sscan(os.Args[2], &base) var orignum, origbase = num, base // Build the result right-to-left, in the string res. res := "" for num > 0 { digit := num % base num /= base if digit < 10 { res = fmt.Sprint(digit) + res } else { res = fmt.Sprintf("%c", 'A'+digit-10) + res } } if(res == "") { res = "0" } fmt.Printf("%d in base %d is %s\n", orignum, origbase, res) }
Notice we're importing two packages. Two separate import statements would have worked as well.

The Sscan method here converts a digit string from the command line to an integer.

The variable res is a string; the := declaration gives it the type of the string constant "".

The os package contains several things to communicate with the underlying operating system. The os.Args is an array containing the contents of the command line as strings, much like argv in plain C.