×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Binary Literals in Golang

By IncludeHelp Last updated : October 05, 2024

Binary numbers

Binary is a number system with base 2, it has 2 values (0 and 1).

Binary Literals in Golang

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

Examples:

0b00
0b11
0B10
0b11100
0b1111
0b11110000

Assigning a binary value to a variable & constant

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

Example of assigning binary values to a variable & a constant

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

package main

import (
	"fmt"
)

func main() {
	// variable
	var a int = 0b1110011
	// constant
	const b int = 0b1111

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

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

Output:

a =  115
b =  15
a = 1110011
b = 1111

Using a binary value in an expression

A binary value can also be used within an expression. In the below program, we are declaring two variables, assigning them with binary values, and finding their sum with a binary value "0b11" which is equivalent to 2.

Example of using binary values in an expression

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

package main

import (
	"fmt"
)

func main() {
	// variables
	a := 0b10011
	b := 0b11111

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

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

Output:

a =  19
b =  31
c =  53
a = 10011
b = 11111
c = 110101



Comments and Discussions!

Load comments ↻





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