Comprender la evaluación bit a bit de una máscara de bits en Objective-C

I'm trying to really wrap my head around this line of code:

[cardButton setTitle:card.contents

What's tripping me up is the bitwise |. How is it different from a normal || or OR?

Why use bitwise | vs. a logical ||?

(For reference, forState:UIControlStateSelected = 1 << 1; UIControlStateDisabled 1 << 2)

preguntado el 05 de mayo de 13 a las 18:05

sorry for my stupid question, but... how beginner are you in software development? -

2 Respuestas

Bitwise OR is different from logical OR in that it performs ORs of individual bits, and does not short-circuit. In contrast, the logical OR siempre produce 1 or 0, and it stops evaluating its arguments as soon as it is clear what answer it is going to get (i.e. as soon as it finds the first non-zero argument in the chain of its arguments).

Specifically for this case, 1 << 1 es binario 10 y 1 << 2 es binario 100, asi que OR-ing them together produces a binary 110o decimal 6. If you were using the logical OR instead, you would simply get 1, because the very first argument, 1 << 1, es distinto de cero.

contestado el 05 de mayo de 13 a las 18:05

In short, a bitwise operation performs the logical operation on the single bits, whereas a logical operation works on the whole value.

In the case of masks, bitwise OR is used so you can compose multiple values in one.

For instance (using 16-bit integers)

0000000000000010 UIControlStateSelected 
0000000000000100 UIControlStateDisabled
0000000000000110 UIControlState Disabled and Selected

A logical evaluation would instead return true since they are both non-zero

contestado el 05 de mayo de 13 a las 18:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.