loading...

Binary Operator Hack and Tricks

lumochift profile image Moch. Lutfi Originally published at lumochift.org on ・1 min read

A 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 operator. Let's explore what tricks behind those operators using go language.

Multiply or Divide By 2

Multiply 2 using * 2 or divide using / 2 is the normal way, but how we can achieve the same with the binary operator?

divide by 2 shift right by 1 someNumber >> 1
multiply by 2 shift left by 1 someNumber << 1
    // multiply by 2
    fmt.Println(4 << 1)
    // Output: 8

    // divide by 2
    fmt.Println(4 >> 1)
    // Output: 2

Change case of character


    // to upper case char
    fmt.Println((string)('c' & '_'))
    // Output: C

    // to lower case char
    fmt.Println(string('A' | ' '))
    // Output: a

Invert case of character

Invert char can be achieved by xor with space

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

Get letter position

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

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

Check number odd or even

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

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

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

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

Discussion

pic
Editor guide