×

Advertisement

# Golang | How can I convert from int to octal?

Golang | Converting from int to octal: Here, we are going to learn how can I convert from int to octal in Go programming language?
Submitted by IncludeHelp, on August 04, 2021

## Converting from int to octal in Golang

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
```

Comments and Discussions!

Student's Section
Subscribe

Copyright © 2024 www.includehelp.com. All rights reserved.