ADVERTISEMENT
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

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".

Program:

// 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.

Program:

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

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.