# 运算符 -- 就要学习 Go 语言

·  阅读 2045

### 算术运算符

``````+    sum                    integers, floats, complex values (复数), strings
-    difference             integers, floats, complex values
*    product                integers, floats, complex values
/    quotient               integers, floats, complex values
%    remainder              integers

&    bitwise AND (按位与)                integers
|    bitwise OR (按位或)                 integers
^    bitwise XOR (按位异或)              integers
&^   bit clear (AND NOT 按位置零)        integers

<<   left shift             integer << unsigned integer
>>   right shift            integer >> unsigned integer

``````var a int8 = 3
var b uint8 = 3
var c int8 = -3

fmt.Printf("^%b=%b %d\n", a, ^a, ^a) // ^11=-100 -4
fmt.Printf("^%b=%b %d\n", b, ^b, ^b) // ^11=11111100 252
fmt.Printf("^%b=%b %d\n", c, ^c, ^c) // ^-11=10 2

``````^11=-100 -4
^11=11111100 252
^-11=10 2

``````var a int8 = 3
var c int8 = 5

fmt.Printf("a: %08b\n",a)
fmt.Printf("c: %08b\n",c)
fmt.Printf("a^c: %08b\n",a ^ c)

``````a: 00000011
c: 00000101
a^c: 00000110

``````var x uint8 = 214
var y uint8 = 92
fmt.Printf("x: %08b\n",x)
fmt.Printf("y: %08b\n",y)
fmt.Printf("x|y: %08b\n",x | y)
fmt.Printf("x&^y: %08b\n",x &^ y)

``````x: 11010110
y: 01011100
x|y: 11011110
x&^y: 10000010

``````var a int8 = -51
fmt.Println("a:")
fmt.Printf("%08b\n",a)
fmt.Printf("%d: %08b\n", a>>1, a>>1)

var b int8 = 51
fmt.Println("b:")
fmt.Printf("%08b\n",b)
fmt.Printf("%d: %08b\n", b>>1, b>>1)

var i uint8 = 1
fmt.Println("i:")
fmt.Printf("%d: %08b\n", i<<1, i<<1) //2: 00000010
fmt.Printf("%d: %08b\n", i<<7, i<<7) //128: 10000000
fmt.Printf("%d: %b\n", i<<8, i<<8) //0: 0
var i2 int8 = 1
fmt.Println("i2:")
fmt.Printf("%d: %08b\n", i2<<1, i2<<1) //2: 00000010
fmt.Printf("%d: %08b\n", i2<<7, i2<<7) //-128: -10000000
fmt.Printf("%d: %b\n", i2<<8, i2<<8) //0: 0
var i3 int8 = -1
fmt.Println("i3:")
fmt.Printf("%d: %08b\n", -i3<<1, -i3<<1) //2: 00000010
fmt.Printf("%d: %08b\n", -i3<<7, -i3<<7) //-128: -10000000
fmt.Printf("%d: %b\n", -i3<<8, -i3<<8) //0: 0
var i4 int8 = -128
fmt.Println("i4:")
fmt.Printf("%d: %08b\n", -i4>>0, -i4>>0) //-128: -10000000
fmt.Printf("%d: %08b\n", -i4>>1, -i4>>1) //-64: -1000000
fmt.Printf("%d: %b\n", -i4>>2, -i4>>2) //-32: -100000

``````a:
-0110011
-26: -0011010
b:
00110011
25: 00011001
i:
2: 00000010
128: 10000000
0: 0
i2:
2: 00000010
-128: -10000000
0: 0
i3:
2: 00000010
-128: -10000000
0: 0
i4:
-128: -10000000
-64: -1000000
-32: -100000

``````c := " Seekload"
s := "Hi" + string(c)
s += ", good bye"

``````var x int8 = 127;
fmt.Printf("%d\n",x+2)   //输出 -127

``````var x uint8 = 255;
fmt.Printf("%d\n",x+2)    // 输出：1

### 逻辑运算符

``````符号  说明
&&   逻辑与  (p && q)  p、q全为true,(p && q)才为true
||   逻辑或  (p || q)  p、q至少一个为true,(p || q)就为true
！   逻辑非   !p  若p为true，则!p为false;若p为false，则!p为true;

### 运算符优先级

``````优先级   操作符
5     *  /  %  <<  >>  &  &^
4     +  -  |  ^
3     ==  !=  <  <=  >  >=
2     &&
1     ||

（全文完）