Base Conversion 1
/* * Read two numbers and print the first one in the base * indicated by the second. */ package main import "fmt" func main() { // Declare two integers variables. var num, base int fmt.Printf("Please enter number and base: ") fmt.Scan(&num, &base) /* Find the largest power of the base <= the number, but not less than one. */ pwr := base for ; pwr <= num; pwr *= base { } pwr = pwr / base fmt.Printf("%d in base %d is ", num, base) /* This for loop is like a while in C or Java. It generates and prints the digits. */ for pwr >= 1 { digit := num / pwr num -= digit*pwr pwr /= base if digit < 10 { fmt.Printf("%d", digit) } else { fmt.Printf("%c", 'A'+digit-10) } } fmt.Printf("\n") }
The first line of main declares two variables. Notice that the type is given last. They are initialized to zero.

The Scan method reads values for the variables. The & operator is like C's address-of operation.

The for loop can be written with a single header expression, in which case it behaves as a while in other languages.

Notice the use of := to declare variables, and the use of = to assign existing ones. The := declares the variable on its left to have the same type as the expression on its right, then initializes the variable to that expression value.