Understanding bit operations and usage scenarios

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

Recently looking at Apue, the example of the function umask used a bitwise operation, which is a very suitable scenario for using bit operations, and it is necessary to take a note. The example code is based on Golang because of the recent learning Golang.

Bit arithmetic

Let's look at the definition of the next operation: all the numbers in the program are stored in binary form in the computer's memory. Bitwise arithmetic is the direct operation of an integer in memory bits. excerpt from Baidu Encyclopedia

For example, the& operation would have been a logical operator, but the integer and integer can also be used for & operations. For example, the binary of 6 is the binary of 110,11 is 1011, then the result of 6 & 11 is 2, it is the result of the logical operation of binary corresponding bit (0 means False,1 means True, the empty space is handled as 0 ), the following code is implemented with go:

func Base() {a:=6//0110B: = One//1011----//&0010=2// |1111= the// ^1101= -&^0100=4Fmt.Println(A & B) fmt.Println(A | b) fmt.Println(a ^ b) fmt.Println(a &^ B)}

The four digit operators are described below:

01101011    0010AND 都为1。011010111111OR 至少一个为1。011010111101XOR 只能一个为1。011010110100AND NOT 清除标志位。

Application Scenario-umask

It's easy to understand the bit arithmetic, but is this bit operation hairy? What scenario is suitable for? Below I use the UNIX system umask concept to practice the next operation. See Http://linux.vbird.org/linux_basic/0220filemanager.php#umask for the concept of umask. Simply put, the UNIX system has 9 permission bits to control the file permissions:

[-][rwx][r-x][r--] 1  234  567  890
    • R: Readable 4
    • W: Writable 2
    • x: Executable 1
    • -: Indicates that this permission is removed

The first bit is used to indicate whether it is a file or a directory, first without the control of it, mainly in the back 9 bits. We often use the authorization is used to 644,755 are r,w.x these three values added. Why the value is 4,2,1 , we put the Go language sys package in the source code to see it understand:

const (    0x100//用户可读    0x80    //用户可写    0x40    //用户可执行    0x20    //组可读    0x10    //组可写    0x8    //组可执行    0x4    //其它可读    0x2    //其它可写    0x1    //其它可执行)

Here are some constants defined in the SYS package, let's print what these are.

Fmt. Printf ("%9b%3d%s\n", S_irusr, S_IRUSR,"User Read") FMT. Printf ("%9b%3d%s\n", S_iwusr, S_IWUSR,"User Write") FMT. Printf ("%9b%3d%s\n", S_ixusr, S_IXUSR,"User Execution") FMT. Printf ("%9b%3d%s\n", S_irgrp, S_IRGRP,"group Read *") FMT. Printf ("%9b%3d%s\n", S_iwgrp, S_IWGRP,"Group Write *") FMT. Printf ("%9b%3d%s\n", S_ixgrp, S_IXGRP,"Group Execution") FMT. Printf ("%9b%3d%s\n", S_iroth, S_iroth,"Other reading *") FMT. Printf ("%9b%3d%s\n", S_iwoth, S_iwoth,"Other Write *") FMT. Printf ("%9b%3d%s\n", S_ixoth, S_ixoth,"Other Execution")//Output100000000  theUser-readable10000000  -Users can write1000000   -Users can perform100000   +Group readable10000   -Group writable +   8Group executable -   4Other readableTen   2Other writable1   1Other executable

See understand, in fact, is the nine permission location is marked 1, with the binary can be very clear representation of the permission bit,4,2,1 that is. So umask can take advantage of this bit operation, the code is as follows:

     PackageMainImport("FMT"        "Golang.org/x/sys/unix"        "OS") func main() {Unix. Umask (0) _, Err: = OS. Create ("foo")ifErr! =Nil{FMT. Println ("Create Error")} UNIX. Umask (Unix. S_irgrp | Unix. S_iwgrp | Unix. S_iroth | Unix. S_iwoth) _, ERR2: = OS. Create ("Bar")ifErr2! =Nil{FMT. Println ("Create Error")        }    }

The above code can be seen, unix.S_IRGRP | unix.S_IWGRP | unix.S_IROTH | unix.S_IWOTH using the bit operation, the program has created two files foo,bar, create bar file, file initial permissions to the group and other readable and writable removal, so we ls -la foo bar can see the output as follows with the command:

[vagrant@mydev ~]$ ls -la foo bar-rw-------. 1 vagrant vagrant 0 Oct 26 02:54 bar-rw-rw-rw-. 1 vagrant vagrant 0 Oct 26 02:54 foo

Then use the two-step mapping instructions for the 9 permission bits:

    100000000  theUser-readable10000000  -Users can write1000000   -Users can perform100000   +Group Readable *10000   -Group Writable * +   8Group executable -   4Other readable *Ten   2Other writable *1   1Other executable---------110110Unix. S_irgrp| Unix. S_iwgrp |Unix. S_iroth| Unix. S_iwoth

umask Four parameters I marked it with a model, that pass | The end result of the bit operation is 110110, the implication is that umask the flag to 1 of the permission bit removed.

Finally, I pasted the permission bit binary print code.

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.