preface
Recently, when learning golang, I found a code that I can’t understand
const ( read byte = 1 << iota wirte exec ) func main() { b := read | exec fmt.Println(b) // Output: 5 }
- I can’t understand because I don’t know
|
What do you mean? - On the other hand, the computer foundation is not solid
Bit operation
-
What is bit operation?
Bit operation is an operation that processes bits or data segments shorter than words through algorithms -
What are the benefits of bit operation?
Bit operations can avoid or reduce the number of cycles required on a data structure, and the efficiency can be doubled, because bit operations are processed in parallel -
What are the disadvantages of computing?
Bit operation code is difficult to write and understand -
The most common example of bit operation
Give file read-write permission in Linuxchmod 777 file_name
1. Understand bitwise operators
A = 0011 1100
B = 0000 1101
---------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
Where can I use it
-
For example, an article has three different states: top, no top, recommended, not recommended, read and not read
-
If we want to confirm this state, we need to create three state attributes in a table: 1 If_top, 2 If_recommended, 3 Has_read
-
But if we use bit operation, we only need to create an attribute position in the table
const (
Top int = 1 < < iota // top state
//(it is recommended to enumerate iota mostly from 1, because the default value of int in golang is 0, which may lead to unexpected misunderstanding)
Recommend // recommend
Read // read
)
func main() {
article := GetArticle()
//Judge whether the article is at the top
if (article & top) == top {
fmt. Println (top of this article)
}
if (article & recommend) == recommend {
fmt. Println (recommended in this article)
}
if (article & read) == read {
fmt. Println (the article has been read)
}
//Output: the article is at the top and has been read
//Delete article top status
articleWithoutTop := DeleteTop(article)
fmt.Println(articleWithoutTop)
}
//Get article status
func GetArticle() int {
//The article has both top and read status (output: 5)
state := top | read
return state
}
//Cancel article top status
func DeleteTop(article int) int {
if (article & top) == top {
return article^top
}
return article
}
- This means that we can easily modify different states, and there is only one parameter to modify the operation of the database
supplement
www.zhihu.com/question/38206659
epilogue
- Thanks for reading
This work adoptsCC agreement, reprint must indicate the author and the link to this article