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!
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.
package main
import (
"fmt"
)
func main() {
num := 10
fmt.Printf("Binary representation of %d is: %b", num, num)
}&)The AND operator (&) checks if both corresponding bits are 1. If both bits are 1, the result is 1; otherwise, the result is 0.
package main
import (
"fmt"
)
func main() {
a := 10
b := 5
result := a & b
fmt.Printf("Result of AND operation is: %d\n", result)
}|)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.
package main
import (
"fmt"
)
func main() {
a := 10
b := 5
result := a | b
fmt.Printf("Result of OR operation is: %d\n", result)
}^)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.
package main
import (
"fmt"
)
func main() {
a := 10
b := 5
result := a ^ b
fmt.Printf("Result of XOR operation is: %d\n", result)
}^)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.
package main
import (
"fmt"
)
func main() {
a := 10
result := ^a
fmt.Printf("Result of NOT operation is: %d\n", result)
}Shift operators (<< and >>) move bits to the left or right.
<<)Left shift (<<) moves bits to the left, filling the vacated positions with 0s.
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 (>>) moves bits to the right, filling the vacated positions with the sign bit (MSB) for signed integers, and 0 for unsigned integers.
package main
import (
"fmt"
)
func main() {
a := -10
b := 2
result := a >> b
fmt.Printf("Result of right shift operation is: %d\n", result)
}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! š»š