Go Bitwise Operators šŸŽÆ

beginner
25 min

Go Bitwise Operators šŸŽÆ

Welcome to our deep dive into Go's Bitwise Operators! These operators allow you to perform low-level manipulations on binary data, which can be incredibly useful for various applications. Let's get started!

Understanding Bitwise Operations šŸ“

Bitwise operations are a set of basic operations that work on the binary representation of numbers. Each number, regardless of its value, is represented as a series of bits (0s and 1s) in the computer's memory. These operations allow us to manipulate individual bits directly.

šŸ’” Pro Tip: You can convert any number to binary using the Go's built-in package fmt.

go
package main import ( "fmt" ) func main() { num := 10 fmt.Printf("Binary representation of %d is: %b", num, num) }

Basic Bitwise Operators šŸ“

AND (&)

The AND operator (&) checks if both corresponding bits are 1. If both bits are 1, the result is 1; otherwise, the result is 0.

go
package main import ( "fmt" ) func main() { a := 10 b := 5 result := a & b fmt.Printf("Result of AND operation is: %d\n", result) }

OR (|)

The OR operator (|) checks if either or both corresponding bits are 1. If at least one bit is 1, the result is 1; otherwise, the result is 0.

go
package main import ( "fmt" ) func main() { a := 10 b := 5 result := a | b fmt.Printf("Result of OR operation is: %d\n", result) }

XOR (^)

The XOR operator (^) checks if either but not both corresponding bits are 1. If one bit is 1 and the other is 0, the result is 1; otherwise, the result is 0.

go
package main import ( "fmt" ) func main() { a := 10 b := 5 result := a ^ b fmt.Printf("Result of XOR operation is: %d\n", result) }

NOT (^)

The NOT operator (^) flips all the bits of a number. If a bit is 1, the result is 0; if a bit is 0, the result is 1.

go
package main import ( "fmt" ) func main() { a := 10 result := ^a fmt.Printf("Result of NOT operation is: %d\n", result) }

Shift Operators šŸ“

Shift operators (<< and >>) move bits to the left or right.

Left Shift (<<)

Left shift (<<) moves bits to the left, filling the vacated positions with 0s.

go
package main import ( "fmt" ) func main() { a := 10 b := 2 result := a << b fmt.Printf("Result of left shift operation is: %d\n", result) }

Right Shift (>>)

Right shift (>>) moves bits to the right, filling the vacated positions with the sign bit (MSB) for signed integers, and 0 for unsigned integers.

go
package main import ( "fmt" ) func main() { a := -10 b := 2 result := a >> b fmt.Printf("Result of right shift operation is: %d\n", result) }

Bitwise Operators Quiz šŸ’”

Quick Quiz
Question 1 of 1

What is the result of the following code?

That's it for our introduction to Go Bitwise Operators! Practice these operators and explore their applications in real-world projects. Happy coding! šŸ’»šŸš€