-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
姚云
committed
May 18, 2020
1 parent
410931d
commit 457a5ef
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
package main | ||
|
||
import "fmt" | ||
|
||
/** Go语言位运算 | ||
位运算都是在二进制的基础上进行运算的,所以在位运算之前要将两个数转成二进制 | ||
& 与 AND 只有两个数都是1结果才为1 | ||
| 或 OR 两个数有一个是1 结果就是1 | ||
^ 异或 XOR ^作二元运算符就是异或,相同为0,不相同为1, ^作一元运算符表示是按位取反(一个有符号位的^操作为 这个数+1的相反数) | ||
&^ 位与非 AND NOT。它是一个 使用 AND 后,再使用 NOT 操作的简写 将运算符左边数据相异的位保留,相同位清零 | ||
<< 左移 左移规则: 右边空出的位用0填补, 高位左移溢出则舍弃该高位 | ||
>> 右移 右移规则:左边空出的位用0或者1填补。正数用0填补,负数用1填补。注:不同的环境填补方式可能不同, 低位右移溢出则舍弃该位 | ||
**/ | ||
func main() { | ||
// & 只有两个数都是1结果才为1 | ||
fmt.Printf("%08b %d\n", 4, 4) // 00000100 4 | ||
fmt.Printf("%08b %d\n", 7, 7) // 00000111 7 | ||
fmt.Printf("%08b %d\n", 4&7, 4&7) // 00000100 4 | ||
|
||
// | 或 两个数有一个是1 结果就是1 | ||
fmt.Printf("%08b %d\n", 4, 4) // 00000100 4 | ||
fmt.Printf("%08b %d\n", 7, 7) // 000000111 7 | ||
fmt.Printf("%08b %d\n", 4|7, 4|7) // 00000111 7 | ||
|
||
// ^作二元运算符就是异或,相同为0,不相同为1 | ||
fmt.Printf("%08b %d\n", 4, 4) // 00000100 4 | ||
fmt.Printf("%08b %d\n", 8, 8) // 00001000 8 | ||
fmt.Printf("%08b %d\n", 4^8, 4^8) // 00001100 12 | ||
|
||
// ^作一元运算符表示是按位取反 | ||
fmt.Printf("%08b %d\n", 8, 8) // 00001000 8 | ||
fmt.Printf("%08b %d\n", ^8, ^8) // -0001001 -9 | ||
fmt.Printf("%08b %d\n", uint8(8), uint8(8)) // 00001000 8 | ||
fmt.Printf("%08b %d\n", ^uint8(8), ^uint8(8)) // 11110111 247 | ||
|
||
// &^ 位与非 AND NOT。它是一个 使用 AND 后,再使用 NOT 操作的简写,相同位清零, 不同位将运算符左边数据相异的位保留 | ||
fmt.Printf("%08b %d\n", 4, 4) // 00000100 4 | ||
fmt.Printf("%08b %d\n", 8, 8) // 00001000 8 | ||
fmt.Printf("%08b %d\n", 4&^8, 4&^8) // 00000100 4 | ||
|
||
var a int8 = -30 | ||
fmt.Printf("%08b %d\n", a, a) // -0011110 -30 | ||
fmt.Printf("%08b %d\n", a>>1, a>>1) // -0001111 -15 | ||
fmt.Printf("%08b %d\n", a>>2, a>>2) // -0001000 -8 | ||
fmt.Printf("%08b %d\n", a>>3, a>>3) // -0000100 -4 | ||
fmt.Printf("%08b %d\n", a>>4, a>>4) // -0000010 -2 | ||
fmt.Printf("%08b %d\n", a>>5, a>>5) // -0000001 -1 | ||
fmt.Printf("%08b %d\n", a>>6, a>>6) // -0000001 -1 ??? 是因为负数运算是取补码? | ||
|
||
a = 3 | ||
fmt.Printf("%08b %d\n", a, a) // 00000011 3 | ||
fmt.Printf("%08b %d\n", a<<1, a<<1) // 00000110 6 | ||
fmt.Printf("%08b %d\n", a<<2, a<<2) // 00001100 12 | ||
fmt.Printf("%08b %d\n", a<<3, a<<3) // 00011000 24 | ||
} |