简体   繁体   中英

In C: what does var = x | y | z; mean?

So I've recently started working with TI's CC2650 device and am trying to learn how to program it by studying some of their sample applications. I see a lot of variables declared in this format and I have no clue what it means:

var1 = x | y | z;

In the example above, var1 is of type uint8_t.

| is the binary bitwise or operator. For example: 0x00ff | 0xff00 0x00ff | 0xff00 is 0xffff .

bitwise OR operator, so if you have x = 5 (101) y = 8 (1000) and z = 20 (10100), values in parenthesis are binary values so x | y | z = 101 | 1000 | 10100 = 11101 x | y | z = 101 | 1000 | 10100 = 11101

The operator | in C is known as bitwise OR operator . Similar to other bitwise operators (say AND & ), bitwise OR only operates at the bit level. Its result is a 1 if one of the either bits is 1 and zero only when both bits are 0 . The | which can be called a pipe! Look at the following:

bit a   bit b   a | b (a OR b)
   0       0       0
   0       1       1
   1       0       1
   1       1       1

In the expression, you mentioned:

var1 = x | y | z | ...;

as there are many | in a single statement, you have to know that, bitwise OR operator has Left-to-right Associativity means the operations are grouped from the left. Hence the above expression would be interpreted as:

var1 = (x | y) | z | ...
=> var1 = ((x | y) | z) | ...
....

Read more about Associativity here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM