Home »
Golang
Golang | How can I convert from int to octal?
By IncludeHelp Last updated : October 05, 2024
There are two ways to convert from int to octal,
1. Int to octal conversion using fmt.Sprintf()
In Golang (other languages also), octal is an integral literal, we can convert octal to int by representing the int in octal (as string representation) using fmt.Sprintf() and %o or %O. %o prints the only octal value and %O prints the octal value prefix with "0o".
Golang code for Int to octal conversion using fmt.Sprintf()
// Golang program for int to octal conversion
// using fmt.Sprintf()
package main
import (
"fmt"
)
func main() {
int_value := 123
oct_value := fmt.Sprintf("%o", int_value)
fmt.Printf("Octal value of %d is = %s\n", int_value, oct_value)
oct_value = fmt.Sprintf("%O", int_value)
fmt.Printf("Octal value of %d is = %s\n", int_value, oct_value)
int_value = 65535
oct_value = fmt.Sprintf("%o", int_value)
fmt.Printf("Octal value of %d is = %s\n", int_value, oct_value)
oct_value = fmt.Sprintf("%O", int_value)
fmt.Printf("Octal value of %d is = %s\n", int_value, oct_value)
}
Output:
Octal value of 123 is = 173
Octal value of 123 is = 0o173
Octal value of 65535 is = 177777
Octal value of 65535 is = 0o177777
2. Int to octal conversion using strconv.FormatInt()
To convert from int to octal, we can also use strconv.FormatInt() method which is defined in strconv package.
Golang code for Int to octal conversion using strconv.FormatInt()
// Golang program for int to octal conversion
// using strconv.FormatInt()
package main
import (
"fmt"
"strconv"
)
func main() {
int_value := 123
oct_value := strconv.FormatInt(int64(int_value), 8)
fmt.Printf("Octal value of %d is = %s\n", int_value, oct_value)
int_value = 65535
oct_value = strconv.FormatInt(int64(int_value), 8)
fmt.Printf("Octal value of %d is = %s\n", int_value, oct_value)
}
Output:
Octal value of 123 is = 173
Octal value of 65535 is = 177777