ADVERTISEMENT
ADVERTISEMENT

Octal Literals in Golang

Golang | Octal: In this tutorial, we are going to learn about the octal literals, how to use octal values in Go Language?
Submitted by IncludeHelp, on April 07, 2021

Octal numbers

Octal is a number system with base 8, it has 8 values (0, 1, 2, 3, 4, 5, 6, and, 7).

In Go programming language, an octal literal can be written with the prefix 0 (Zero). The value which is prefixed with 0 is considered as an octal value and it can be used in the program statements like an octal value can be assigned to a variable or constant, can be used within an expression, can be assigned in an array, etc.

Examples:

01234
07654
077

Assigning an octal value to a variable & constant

In the below example, we are creating a variable and a constant, and assigning octal values to them.

Example of assigning octal values to a variable & a constant

// Golang program to demonstrate the example of
// assigning octal values to
// a variable & a constant

package main

import (
	"fmt"
)

func main() {
	// variable
	var a int = 012345
	// constant
	const b int = 076

	// printing the values
	fmt.Println("a = ", a)
	fmt.Println("b = ", b)

	// printing values in the octal format
	fmt.Printf("a = %o\n", a)
	fmt.Printf("b = %o\n", b)
}

Output:

a =  5349
b =  62
a = 12345
b = 76

Using an octal value in an expression

An octal value can also be used within an expression. In the below program, we are declaring two variables, assigning them with octal values, and finding their sum with an octal value 076 which is equivalent to 62.

Example of using octal values in an expression

// Golang program to demonstrate the example of
// Example of using octal values
// in an expression

package main

import (
	"fmt"
)

func main() {
	// variables
	a := 010
	b := 020

	// calculating the sum of a, b and 076
	c := a + b + 076
	// printing the values
	fmt.Println("a = ", a)
	fmt.Println("b = ", b)
	fmt.Println("c = ", c)

	// printing values in the octal format
	fmt.Printf("a = %o\n", a)
	fmt.Printf("b = %o\n", b)
	fmt.Printf("c = %o\n", c)
}

Output:

a =  8
b =  16
c =  86
a = 10
b = 20
c = 126

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.