Skip to content
Related Articles

Related Articles

Bitwise NOT operator in Golang
  • Last Updated : 05 May, 2020

Bitwise NOT operator in the programming world usually takes one number and returns the inverted bits of that number as shown below:

Bitwise NOT of 1 = 0
Bitwise NOT of 0 = 1


Input : X = 010101
Output : Bitwise NOT of X = 101010

But Golang doesn’t have any specified unary Bitwise NOT(~) or you can say Bitwise Complement operator like other programming languages(C/C++, Java, Python, etc). Here, you have to use Bitwise XOR(^) operator as Bitwise NOT operator. But how?

Let’s understand how Bitwise XOR takes in any two equal length bit patterns and performs Exclusive OR operation on each pair of corresponding bits.

1 XOR 1 = 0 
1 XOR 0 = 1 
0 XOR 0 = 0
0 XOR 1 = 1 

Here, you can see the result of XOR(M, N) = 1 only if M != N else it will be 0. So here, we will use the XOR operator as a unary operator to implement the one’s complement to a number.
In Golang, suppose you have a given bit M, so ^M = 1 ^ M which will be equal to one’s complement or you can say the Bitwise NOT operator result.

Example: Suppose you have the given bits as 010101.

Input: 11111111 XOR 00001111
Output: 11110000

package main
import "fmt"
func main() {
    // taking the number in the hexadecimal
    // form it is 15 i.e. 00001111 in 8-bit form
    var bitwisenot byte = 0x0F
    // printing the number in 8-Bit
    fmt.Printf("%08b\n", bitwisenot) 
    // using the ^M = 1 ^ M
    fmt.Printf("%08b\n", ^bitwisenot)



Here, you can see, if we simply solve the Bitwise Not of 00001111 then it will be equal to 11110000.

My Personal Notes arrow_drop_up
Recommended Articles
Page :