Bitwise NOT operator in Golang

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

Example:

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
filter_none

edit
close

play_arrow

link
brightness_4
code

   
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)
}

chevron_right


Output:

00001111
11110000

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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.