Go Tutorials

Go Programs

Go Convert Decimal to Octal


Go Convert Decimal to Octal

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
}


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,

  1. Define a function named decimalToOctal that takes one parameter n of type int.
  2. Check if n is 0. If true, return '0'.
  3. Initialize an empty string octal to store the octal representation.
  4. Use a for loop to repeatedly divide n by 8 and prepend the remainder to octal until n becomes 0.
  5. Return the octal representation as a string.
  6. 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