Nice programing

부울 연산자와 비트 연산자

nicepro 2020. 11. 24. 19:56
반응형

부울 연산자와 비트 연산자


부울 대 비트 연산자를 사용해야 할 때 혼란 스럽습니다.

  • and vs &
  • or vs |

누군가 내가 언제 각각을 사용하고 다른 하나를 사용하는 것이 내 결과에 영향을 미치는지에 대해 가르쳐 줄 수 있습니까?


다음은 몇 가지 지침입니다.

  • 부울 연산자는 일반적으로 부울 값에 사용되지만 비트 연산자는 일반적으로 정수 값에 사용 됩니다.
  • 부울 연산자는 단락 되지만 비트 연산자는 단락 되지 않습니다 .

단락 동작은 다음과 같은 식에서 유용합니다.

if x is not None and x.foo == 42:
    # ...

&양측이 항상 평가되어를 제공하므로 비트 연산자 에서는 올바르게 작동하지 않습니다 AttributeError: 'NoneType' object has no attribute 'foo'. 부울 and연산자 를 사용하는 경우 첫 번째 표현식이 False이면 두 번째 표현식이 평가되지 않습니다. 마찬가지로 or첫 번째 인수가 True이면 두 번째 인수를 평가하지 않습니다.


이론적 andor부울 로직 곧게 (따라서 부울 생산 개의 부울상에서 동작) 동안 &|그리고 / 또는 정수의 개별 비트 부울을 적용한다. 후자가 정확히 어떻게 작동하는지에 대한 많은 질문이 있습니다.

결과에 잠재적으로 영향을 미칠 수있는 실질적인 차이점은 다음과 같습니다.

  1. andor단락은, 즉, True or sys.exit(1)어떤 이유로 값 (들어, 종료하지 것 True or ..., False and ...첫 번째 오퍼랜드의) 결과를 변경하지 않을 두번째는 = 평가 될 필요가 없다. 그러나 |&단락을 - True | sys.exit(1)REPL 나갔어을 던졌습니다.
  2. (일부 적용 파이썬을 포함하여 연산자 오버로딩과 언어, :)? &그리고 |정기적으로 운영하고 오버로드 할 수 있습니다 - and그리고 or파이썬에서 적어도 부울로 강제하기위한 특별한 방법은 부작용이있을 수 있지만) (언어로 단조된다.
  3. (몇 언어에 적용 [KennyTM의 의견을 참조] : andor)를 대신 피연산자의 값 반환 (항상? 정말 이것을 이해하지 않으며 내가 필요했던 True또는 False. -이 조건에서 부울 식의 의미를 변경하지 않습니다 1 or True입니다 1만, 1역시 사실이다. 그러나 한때 조건부 연산자를 에뮬레이트하는 데 사용되었습니다 ( cond ? true_val : false_valC 구문에서는 true_val if cond else false_val몇 년 동안 Python에서). 들어 &|, 결과 유형은 (피연산자는 각각의 특별한 방법에 과부하 방법에 따라 달라집니다 True & False이다 False, 99 & 7입니다 3... 그것의 조합 / 교차 세트에 대한).

예를 들어, 심지어 때 a_boolean & another_boolean동일하게 작동합니다, 최적의 솔루션을 사용하고 and있기 때문에 단순히 - andor동안 부울 표현식과 조건과 관련된 &|비트 만지작 약자.


다음은 &(및 기타 비트 연산자)가 and(및 다른 부울 연산자) 보다 우선 순위가 높기 때문에 다음식이 다른 값으로 평가 되기 때문에 잠시 동안 당혹 스러웠던 추가 차이점 있습니다.

0 < 1 & 0 < 2

0 < 1 and 0 < 2

즉, 첫 번째 False0 < (1 & 0) < 2, 따라서 0 < 0 < 2, 따라서 0 < 0 and 0 < 2.


에서 요소 별 부울 연산을 수행하려는 경우 numpy대답이 다소 다릅니다. 당신은 사용할 수 있습니다 &|요소 현명한 부울 작업 만 and하고 or값 오류를 반환합니다.

안전을 위해 numpy 논리 함수를 사용할 수 있습니다 .

np.array([True, False, True]) | np.array([True, False, False])
# array([ True, False,  True], dtype=bool)

np.array([True, False, True]) or np.array([True, False, False])
# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

np.logical_or(np.array([True, False, True]), np.array([True, False, False]))
# array([ True, False,  True], dtype=bool)

부울 연산은 논리 연산입니다.

비트 연산은 이진 비트에 대한 연산입니다.

비트 연산 :

>>> k = 1
>>> z = 3
>>> k & z  
1
>>> k | z  
3

작업 :

And & 1 if both bits are 1, 0 otherwise
Or  | 1 if either bit is 1
Xor ^ 1 if the bits are different, 0 if they're the same
Not ~ Flip each bit

비트 연산의 일부 사용 :

1) 비트 설정 및 삭제

부울 연산 :

>>> k = True
>>> z = False
>>> k & z  # and
False
>>> k | z  # or
True
>>> 

힌트는 이름에 있습니다.

  • 부울 연산자는 논리 연산 을 수행하기위한 것입니다 (프로그래밍 및 형식 논리에서 일반적인 진실 테스트).
  • Bitwise operators are for "bit-twiddling" (low level manipulation of bits in byte and numeric data types)

While it is possible and indeed sometimes desirable (typically for efficiency reasons) to perform logical operations with bitwise operators, you should generally avoid them for such purposes to prevent subtle bugs and unwanted side effects.

If you need to manipulate bits, then the bitwise operators are purpose built. The fun book: Hackers Delight contains some cool and genuinely useful examples of what can be achieved with bit-twiddling.


The general rule is to use the appropriate operator for the existing operands. Use boolean (logical) operators with boolean operands, and bitwise operators with (wider) integral operands (note: False is equivalent to 0, and True to 1). The only "tricky" scenario is applying boolean operators to non boolean operands.
Let's take a simple example, as described in [SO]: Python - Differences between 'and' and '&': 5 & 7 vs. 5 and 7.

For the bitwise and (&), things are pretty straightforward:

5     = 0b101
7     = 0b111
-----------------
5 & 7 = 0b101 = 5

For the logical and, here's what [Python 3]: Boolean operations states (emphasis is mine):

(Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument.

Example:

>>> 5 and 7
7
>>> 7 and 5
5

Of course, the same applies for | vs. or.


Boolean 'and' vs. Bitwise '&':

Pseudo-code/Python helped me understand the difference between these:

def boolAnd(A, B):
    # boolean 'and' returns either A or B
    if A == False:
        return A
    else:
        return B

def bitwiseAnd(A , B):
    # binary representation (e.g. 9 is '1001', 1 is '0001', etc.)

    binA = binary(A)
    binB = binary(B)



    # perform boolean 'and' on each pair of binaries in (A, B)
    # then return the result:
    # equivalent to: return ''.join([x*y for (x,y) in zip(binA, binB)])

    # assuming binA and binB are the same length
    result = []
    for i in range(len(binA)):
      compar = boolAnd(binA[i], binB[i]) 
      result.append(compar)

    # we want to return a string of 1s and 0s, not a list

    return ''.join(result)

Logical Operations

are usually used for conditional statements. For example:

if a==2 and b >10 then /*Do something...*/ endif It means if both conditions((a==2) (b>10)) are true at the same time then conditional statement body can be executed.

Bitwise Operations

Bitwise operations can be used for data manipulation and extraction. For example, if you want to extract four LSB(Least Significant Bits) of an integer, you can do this:

Extraction:

poo & 0x000F

Masking:

poo | 0xFFF0

참고URL : https://stackoverflow.com/questions/3845018/boolean-operators-vs-bitwise-operators

반응형