ADVERTISEMENT
ADVERTISEMENT

Golang Bitwise Operators

Here, we are going to learn about the Bitwise Operators in the Go programming language with examples.
Submitted by IncludeHelp, on December 07, 2021

Bitwise Operators

Bitwise operators are used for performing operations on bits, i.e., bitwise operators work on bits and perform the bit-by-bit operation, i.e., the bitwise operators are the operators used to perform bitwise operations on bit patterns or binary numerals that involve the manipulation of individual bits.

List of Golang Bitwise Operators

Operator Description Example
x:=5
y:=3
Bitwise AND (&) It returns 1 in each bit position for which the corresponding bits of both operands are 1s. x & y returns 1
Bitwise OR (|) It returns 1 in each bit position for which the corresponding bits of either or both operands are 1s. x | y returns 7
Bitwise XOR (^) It returns 1 in each bit position for which the corresponding bits of either but not both operands are 1s. x ^ y returns 6
Bitwise Left Shift (<<) It shifts the first operand to the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. x << 2 returns 20
Bitwise Right Shift (>>) It shifts the first operand to the specified number of bits to the right. Excess bits shifted off to the right are discarded. x >> 1 returns 1

Example of Golang Bitwise Operators

The below Golang program is demonstrating the example of bitwise operators.

// Golang program demonstrate the
// example of bitwise operators

package main

import "fmt"

func main() {
	x := 5
	y := 3
	result := 0

	result = (x & y)
	fmt.Println(x, "&", y, "=", result)

	result = (x | y)
	fmt.Println(x, "|", y, "=", result)

	result = (x ^ y)
	fmt.Println(x, "^", y, "=", result)

	result = (x << 2)
	fmt.Println(x, "<<", 2, "=", result)

	result = (x >> 2)
	fmt.Println(x, ">>", 2, "=", result)
}

Output:

5 & 3 = 1
5 | 3 = 7
5 ^ 3 = 6
5 << 2 = 20
5 >> 2 = 1

ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



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