Skip to content

Instantly share code, notes, and snippets.

@thejhh
Last active October 29, 2024 08:09
Show Gist options
  • Save thejhh/d917838f3e181da3ed2c2660d3cf2669 to your computer and use it in GitHub Desktop.
Save thejhh/d917838f3e181da3ed2c2660d3cf2669 to your computer and use it in GitHub Desktop.
GoLang binary operations

GoLang binary operators

Binary operators

Operation Symbol Example Result Description
AND & 10101010 & 11001100 10001000 1 if both bits are 1
OR | 10101010 | 11001100 11101110 1 if at least one bit is 1
XOR ^ 10101010 ^ 11001100 01100110 1 if bits are different
NOT ^ ^10101010 01010101 Flips each bit
AND NOT &^ 10101010 &^ 11001100 00100010 Clears bits where second operand has 1s
Left Shift << 00001111 << 2 00111100 Shifts bits left, fills in with 0s
Right Shift >> 11110000 >> 2 00111100 Shifts bits right, fills in with 0s

Binary assignment operators

Operation Symbol Example Result Description
OR |= a |= b a = a | b Sets bits to 1 if either a or b has 1 at that position
AND &= a &= b a = a & b Sets bits to 1 only if both a and b have 1
XOR ^= a ^= b a = a ^ b Toggles bits where a and b differ
AND NOT &^= a &^= b a = a &^ b Clears bits in a where b has 1s
Left Shift <<= a <<= n a = a << n Shifts bits in a left by n positions, filling with 0s
Right Shift >>= a >>= n a = a >> n Shifts bits in a right by n positions, filling with 0s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment