The use of the bitwise operator of the Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

&      位运算 AND|      位运算 OR^      位运算 XOR&^     位清空 (AND NOT)<<     左移>>     右移

Although the sense bit operator is not used much at ordinary times, it is more interesting when it comes to underlying performance optimizations or the use of certain trick.

& (And) | (OR) Do not mention that the most commonly used things will be programmed.

& operation is only retained when two numbers are required to be 1. For example 0000 0100 & 0000 1111 = 0000 0100 = 4

| The operation is maintained when two numbers are at the same time 1 or 1 for 11 not 1. For example 0000 0100 | 0000 1111 = 0000 1111 = 15

^ (XOR) in the Go language, XOR is present as a two-dollar operator:

But if it appears as a unary operator, he means to take a bitwise inverse, for example

Package Mainimport "FMT" Func Main () {    x: = 4    fmt. Println (^x)}output:-5

If the operator is a two-dollar

Package Mainimport "FMT" Func Main () {    x: = 4    y: = 2    fmt. Println (x^y)}output:6

XOR is not a carry addition calculation, that is, XOR or computation. 0000 0100 + 0000 0010 = 0000 0110 = 6

The &^ (and not) bit emptying operation is related to the position of the operator variable, first look at an example:

Package Mainimport "FMT" Func Main () {    x: = 2    y: = 4    fmt. Println (x&^y)}output:2

x&^y==x& (^y) First we convert to 2 binary 0000 0010 &^ 0000 0100 = 0000 0010 If the number on the Ybit bit is 0 then the value of the corresponding position on X, if the ybit bit is 1 then the result bit is taken 0

>> right shift << left shift feel right shift left should also be very common using the continue to see example:

Package Mainimport "FMT" Func Main () {    x: = 2    y: = 4    fmt. Println (x<<1)    FMT. Println (y>>1)}output:4 2

Convert to binary and move left or right.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.