-1

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.

royhowie
  • 11,075
  • 14
  • 50
  • 67
Nick
  • 95
  • 9
  • I wasn't even aware it was a C logical operator. so I didn't even know to google that. – Nick Aug 06 '15 at 03:58
  • possible duplicate of [Java | operator with integers;](http://stackoverflow.com/questions/17640933/java-operator-with-integers) – phuclv Aug 06 '15 at 05:33

3 Answers3

8

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

M. Shaw
  • 1,742
  • 11
  • 15
5

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

E. Moffat
  • 3,165
  • 1
  • 21
  • 34
1

The operator | in C is known a s 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.

Community
  • 1
  • 1
mazhar islam
  • 5,561
  • 3
  • 20
  • 41
  • I think it might be better to say that the operation `or` is a symmetric (commutative) and is both left and right associative. – M. Shaw Aug 06 '15 at 03:50
  • @M.Shaw, don't messed with logical _OR_ `||` and bitwise _OR_ `|`. – mazhar islam Aug 06 '15 at 03:52
  • Sorry, I removed the 2nd part - but the operation is still commutative and both left and right associative. – M. Shaw Aug 06 '15 at 03:55
  • @M.Shaw, take a look [Group 11 precedence, left to right associativity](https://msdn.microsoft.com/en-us/library/126fe14k.aspx). – mazhar islam Aug 06 '15 at 04:05
  • It is a design choice (or perhaps arbitrary) to decide that it is left-to-right associative. It is quite obvious that `a | b == b | a` and `(a | b) | c == a | (b | c)` for any `a,b,c`. If the compiler. – M. Shaw Aug 06 '15 at 04:10