×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Binary Literals in Golang

Last Updated : April 19, 2025

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

Go Binary Literals Exercise

Select the correct option to complete each statement about binary literals in Go.

  1. Binary literals in Go start with the prefix ___.
  2. The binary literal 0b1010 is equal to ___ in decimal.
  3. Binary literals were introduced in Go version ___.

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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