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

Go

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