Bitwise Operations

Go allows bit-wise operations in its language. This allows high-speed flag masking and low-level hardware interaction (if played nicely). In this section, we will look through the operations for bit manipulations. To know the basic of bits and math, you can visit the theory page.

Operators

For Go, however, the operators have some slight differences across various languages. They are:

 &   bitwise AND
 |   bitwise OR
 ^   bitwise XOR
&^   AND NOT
<<   left shift
>>   right shift
^var NOT

NOTE

  • There is one extra: AND NOT
    • This is for clearing bit with mask, a combined version of AND then NOT. Example:
    • In C: 0xFF & ~0x0F = 0xF0
    • In C: 0xAB & ~0x0F = 0xA0
    • In Go: 0xFF &^ 0x0F = 0xF0
    • In Go: 0xAB &^ 0x0F = 0xA0
  • There is one special symbol: NOT. Go doesn't support tilde (~) for bitwise operations.
    • In C: ~0x0F = 0xF0
    • in Go: ^0x0F = 0xF0

Basic Bit Operations

Now let's get into bit-wise operations. Here, we are looking at basic masking:

Selecting Bits

To select bits, you use the & operator.

0xAC & 0xF0 = 0xA0
0b10101100 & 0b11110000 = 0b10100000

Clearing Bits

To clear bits, you use the &^ operator.

0xAC &^ 0xF0 = 0x0C
0b10101100 &^ 0b11110000 = 0b00001100

Set Bits

To set the bits, you use the | operator.

0xAC | 0xF0 = 0xFC
0b10101100 | 0b11110000 = 0b11111100

Flipping Bits

To flip the bits, you use the ^ (XOR) operator.

0xAC ^ 0xF0 = 0x5C
0b10101100 ^ 0b11110000 = 0b01011100

Shifting Operations

Now let's get into bit-wise shifting operations. You can either shift left or shift right by position numbers. Example:

0xAC & (1<<7) = 0x80
0b10101100 & 0b10000000 = 0b10000000

Shift right will moves from the opposite side.

Bit Assignment

One thing to take note is that Go does not have binary literals (e.g. 0b00001010). Hence, the only best and easy way for you to set bit is to use shifting. Example:

  • 0b00001010 = (1 << 3) | (1 << 1)

That's all about bit-wise operations. Now you can switch 32 switches / 64 switches simultaneously depending on your processor, and save a lot of memory space too.