Convert Decimal to Octal in Go
In this tutorial, we will learn how to convert a decimal number to octal in Go. We will cover the basic concept of octal numbers and implement a function to perform the conversion.
What is Octal Conversion
Octal conversion is the process of converting a decimal (base-10) number to an octal (base-8) number. In octal, numbers are represented using digits from 0 to 7.
Syntax
The syntax to convert a decimal number to octal in Go is:
func decimalToOctal(n int) string {
if n == 0 {
return "0"
}
octal := ""
for n > 0 {
remainder := n % 8
octal = fmt.Sprintf("%d%s", remainder, octal)
n = n / 8
}
return octal
}
Example 1: Converting a decimal number to octal
We can create a function to convert a given decimal number to octal by repeatedly dividing the number by 8 and keeping track of the remainders.
For example,
- Define a function named
decimalToOctal
that takes one parametern
of typeint
. - Check if
n
is 0. If true, return '0'. - Initialize an empty string
octal
to store the octal representation. - Use a
for
loop to repeatedly dividen
by 8 and prepend the remainder tooctal
untiln
becomes 0. - Return the octal representation as a string.
- In the main function, call the
decimalToOctal
function with a sample number and print the result.
Go Program
package main
import (
"fmt"
)
func decimalToOctal(n int) string {
if n == 0 {
return "0"
}
octal := ""
for n > 0 {
remainder := n % 8
octal = fmt.Sprintf("%d%s", remainder, octal)
n = n / 8
}
return octal
}
func main() {
// Convert 10 to octal
result := decimalToOctal(10)
// Print the result
fmt.Printf("Octal representation of 10 is %s\n", result)
}
Output
Octal representation of 10 is 12