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.
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 NOTAND NOT0xFF & ~0x0F = 0xF00xAB & ~0x0F = 0xA00xFF &^ 0x0F = 0xF00xAB &^ 0x0F = 0xA0NOT. Go doesn't support tilde (~) for bitwise operations. ~0x0F = 0xF0^0x0F = 0xF0Now let's get into bit-wise operations. Here, we are looking at basic masking:
To select bits, you use the & operator.
0xAC & 0xF0 = 0xA00b10101100 & 0b11110000 = 0b10100000To clear bits, you use the &^ operator.
0xAC &^ 0xF0 = 0x0C0b10101100 &^ 0b11110000 = 0b00001100To set the bits, you use the | operator.
0xAC | 0xF0 = 0xFC0b10101100 | 0b11110000 = 0b11111100To flip the bits, you use the ^ (XOR) operator.
0xAC ^ 0xF0 = 0x5C0b10101100 ^ 0b11110000 = 0b01011100Now let's get into bit-wise shifting operations. You can either shift left or shift right by position numbers. Example:
0xAC & (1<<7) = 0x800b10101100 & 0b10000000 = 0b10000000Shift right will moves from the opposite side.
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.