Directly access/manipulate the bits of an integer
Go is very similar to C, so we expect Go has the same bitwise operator as C does. Based on the langauge spec, Go has the following bit-level operators.
& bitwise AND integers | bitwise OR integers ^ bitwise XOR integers &^ bit clear (AND NOT) integers
<< left shift integer << unsigned integer >> right shift integer >> unsigned integer
The following code I wrote demonstrates the bit-level operation in Go.
// go run bits.go
package main
import "fmt"
func main() {
var i1 int = 0xFF;
var i2 int = 0x04;
var i3 int = 0xF0;
var i4 int = 0x0F;
fmt.Printf("0x%02X bitwise AND 0x%02X is 0x%02X\n", i1, i2, i1 & i2);
fmt.Printf("0x%02X bitwise OR 0x%02X is 0x%02X\n", i3, i4, i3 | i4);
fmt.Printf("0x%02X >> 1 is 0x%02X\n", i3, i3 >> 1);
fmt.Printf("0x%02X bitwise XOR 0x%02X is 0x%02X\n", i3, i4, i3 ^i4);
fmt.Printf("0x%02X bit clear 0x%02X is 0x%02X\n", i1, i3, i1 &^ i3);
}
You should see the following result:
0xFF bitwise AND 0x04 is 0x04
0xF0 bitwise OR 0x0F is 0xFF
0xF0 >> 1 is 0x78
0xF0 bitwise XOR 0x0F is 0xFF
0xFF bit clear 0xF0 is 0x0F