Bitwise operators in Go work on binary numbers, allowing manipulation at the bit level. These operators perform operations directly on the binary representations of values, making them essential for tasks that require fine-grained control over individual bits.
List of Bitwise Operators
Here’s an overview of the available bitwise operators, their functionality, and usage examples:
Operator | Name | Description | Example |
---|---|---|---|
& | AND | Sets each bit to 1 if both corresponding bits are 1. | x & y |
| | OR | Sets each bit to 1 if at least one of the corresponding bits is 1. | x | y |
^ | XOR | Sets each bit to 1 if only one of the corresponding bits is 1. | x ^ b |
<< | Zero fill left shift | Shifts bits to the left, adding zeros from the right. | x << 2 |
>> | Signed right shift | Shifts bits to the right, filling with the leftmost bit’s value. | x >> 3 |
Examples Using Bitwise Operators
package main import "fmt" func main() { ducati := 42 // Binary: 00101010 yamaha := 56 // Binary: 00111000 // AND resultAND := ducati & yamaha fmt.Println("AND result:", resultAND) // Binary: 00101000, Decimal: 40 // OR resultOR := ducati | yamaha fmt.Println("OR result:", resultOR) // Binary: 00111010, Decimal: 58 // XOR resultXOR := ducati ^ yamaha fmt.Println("XOR result:", resultXOR) // Binary: 00010010, Decimal: 18 // Zero fill left shift shiftLeft := ducati << 2 fmt.Println("Left shift result:", shiftLeft) // Binary: 10101000, Decimal: 168 // Signed right shift shiftRight := yamaha >> 3 fmt.Println("Right shift result:", shiftRight) // Binary: 00000111, Decimal: 7 }
Explanation of Examples
- AND (
&
):- Each bit of
ducati
andyamaha
is compared. The result is1
only when both bits are1
.
- Each bit of
- OR (
|
):- Combines the bits from both values. The result is
1
if at least one of the corresponding bits is1
.
- Combines the bits from both values. The result is
- XOR (
^
):- Compares each bit; sets the result to
1
if only one of the bits is1
.
- Compares each bit; sets the result to
- Left Shift (
<<
):- Shifts bits to the left, filling with zeros on the right. This is equivalent to multiplying the value by
2^n
(wheren
is the number of positions shifted).
- Shifts bits to the left, filling with zeros on the right. This is equivalent to multiplying the value by
- Right Shift (
>>
):- Shifts bits to the right, filling with the leftmost bit’s value. This operation is equivalent to dividing the value by
2^n
.
- Shifts bits to the right, filling with the leftmost bit’s value. This operation is equivalent to dividing the value by