Go Bitwise Operators

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.

Tutorials dojo strip



List of Bitwise Operators

Here’s an overview of the available bitwise operators, their functionality, and usage examples:

OperatorNameDescriptionExample
&ANDSets each bit to 1 if both corresponding bits are 1.x & y
|ORSets each bit to 1 if at least one of the corresponding bits is 1.x | y
^XORSets each bit to 1 if only one of the corresponding bits is 1.x ^ b
<<Zero fill left shiftShifts bits to the left, adding zeros from the right.x << 2
>>Signed right shiftShifts 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

  1. AND (&):
    • Each bit of ducati and yamaha is compared. The result is 1 only when both bits are 1.
  2. OR (|):
    • Combines the bits from both values. The result is 1 if at least one of the corresponding bits is 1.
  3. XOR (^):
    • Compares each bit; sets the result to 1 if only one of the bits is 1.
  4. Left Shift (<<):
    • Shifts bits to the left, filling with zeros on the right. This is equivalent to multiplying the value by 2^n (where n is the number of positions shifted).
  5. 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.
Tutorials dojo strip
Scroll to Top