Published on

Binary Operator Hack and Tricks

Authors

Binary operator is a way to manipulate binary data. We already know there are &, |, ^, << and >> operators, but not all of us know the secret of each operators. Let's explore what tricks behind those operator using go language.

Multiply or Divide By 2

We already know how multiply 2 using * 2 or divide using / 2, but how we can achieve same with binary operator?

divide by 2shift right by 1someNumber >> 1
multiply by 2shift left by 1someNumber << 1

_7
// multiply by 2
_7
fmt.Println(4 << 1)
_7
// Output: 8
_7
_7
// divide by 2
_7
fmt.Println(4 >> 1)
_7
// Output: 2

Change case of character

| | | | | ------------------- | ------------------------- | ------------ | ---- | ---- | | change to uppercase | use & with underscore | 'c' & '_' | | change to lowercase | use |withspace | 'A' | ' ' |


_8
_8
// to upper case char
_8
fmt.Println((string)('c' & '_'))
_8
// Output: C
_8
_8
// to lower case char
_8
fmt.Println(string('A' | ' '))
_8
// Output: a

Invert case of character

Invert char can be achieved by xor with space


_2
fmt.Println(string('A' ^ ' '), string('b' ^ ' '))
_2
// Output: a B

Get letter position

Get letter's position in alphabet (1-26) using and with 31


_2
fmt.Println('z' & 31)
_2
// Output: 26

Check number odd or even

Simple check if number is odd/even using and with 1, odd number will return true


_7
// odd number return true
_7
fmt.Println(7 & 1 > 0)
_7
// Output: true
_7
_7
// even number return false
_7
fmt.Println(8 & 1 > 0)
_7
// Output: false

Try it yourself at https://play.golang.org/p/-wsIlDgBTmF