Boolean operators vs Bitwise operators












56















I am confused as to when I should use a Boolean vs Bitwise operators



and vs &, or vs |


Could someone enlighten me as to when do i use each and when will using one over the other affect my results?










share|improve this question




















  • 13





    Note that the answers you'll get roughly apply to about all other (mainstream imperative) languages as well.

    – user395760
    Oct 2 '10 at 8:54
















56















I am confused as to when I should use a Boolean vs Bitwise operators



and vs &, or vs |


Could someone enlighten me as to when do i use each and when will using one over the other affect my results?










share|improve this question




















  • 13





    Note that the answers you'll get roughly apply to about all other (mainstream imperative) languages as well.

    – user395760
    Oct 2 '10 at 8:54














56












56








56


18






I am confused as to when I should use a Boolean vs Bitwise operators



and vs &, or vs |


Could someone enlighten me as to when do i use each and when will using one over the other affect my results?










share|improve this question
















I am confused as to when I should use a Boolean vs Bitwise operators



and vs &, or vs |


Could someone enlighten me as to when do i use each and when will using one over the other affect my results?







python bitwise-operators boolean-operations






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 25 '17 at 3:41









martineau

67.1k1089180




67.1k1089180










asked Oct 2 '10 at 8:52









Jiew MengJiew Meng

20.6k141372636




20.6k141372636








  • 13





    Note that the answers you'll get roughly apply to about all other (mainstream imperative) languages as well.

    – user395760
    Oct 2 '10 at 8:54














  • 13





    Note that the answers you'll get roughly apply to about all other (mainstream imperative) languages as well.

    – user395760
    Oct 2 '10 at 8:54








13




13





Note that the answers you'll get roughly apply to about all other (mainstream imperative) languages as well.

– user395760
Oct 2 '10 at 8:54





Note that the answers you'll get roughly apply to about all other (mainstream imperative) languages as well.

– user395760
Oct 2 '10 at 8:54












8 Answers
8






active

oldest

votes


















52














Here are a couple of guidelines:




  • Boolean operators are usually used on boolean values but bitwise operators are usually used on integer values.

  • Boolean operators are short-circuiting but bitwise operators are not short-circuiting.


The short-circuiting behaviour is useful in expressions like this:



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


This would not work correctly with the bitwise & operator because both sides would always be evaluated, giving AttributeError: 'NoneType' object has no attribute 'foo'. When you use the boolean andoperator the second expression is not evaluated when the first is False. Similarly or does not evaluate the second argument if the first is True.






share|improve this answer





















  • 10





    Supplementary: In Python &, |, ^ are set operations too.

    – kennytm
    Oct 2 '10 at 9:14






  • 3





    Additional supplementary: in Python, bit-wise will not allow mixed types, but boolean will. e.g. True or "True" is fine (it will return the first truthy value), but True | "True" will throw an exception.

    – Hannele
    Feb 10 '16 at 19:11








  • 4





    @Hannele That has nothing to do with mixed types. Bitwise operations only make sense with integers and any other type will throw an exception. The point here is that Python treats False and True as 0 and 1 respectively: 0 == False and 1 == True are both true.

    – Nuno André
    Jul 30 '16 at 17:53






  • 1





    @NunoAndré True enough, that is a more accurate explanation. Thanks!

    – Hannele
    Aug 9 '16 at 5:48






  • 1





    Thank you! That was educational

    – MaxPY
    May 16 '17 at 17:00



















18














In theory, and and or come straight from boolean logic (and therefore operate on two booleans to produce a boolean), while & and | apply the boolean and/or to the individual bits of integers. There are a lot lot of questions here on how the latter work exactly.



Here are practical differences that potentially affect your results:





  1. and and or short-circuiting, i.e. True or sys.exit(1) will not exit, because for a certain value (True or ..., False and ...) of the first operand, the second one wouldn't change the result = does not need to be evaluated. But | and & don't short-circuit - True | sys.exit(1) throws you outta the REPL.

  2. (Only applies to some? languages with operator overloading, including Python:) & and | are regular operators and can be overloaded - and and or are forged into the language (although at least in Python, the special method for coercion to boolean may have side effects).

  3. (only applies to a few languages [see KennyTM's comment]:) and and or return (always? never really understand this, nor did I need it) the value of an operand instead of True or False. This doesn't change the meaning of boolean expressions in conditions - 1 or True is 1, but 1 is true, too. But it was once used to emulate a conditional operator (cond ? true_val : false_val in C syntax, true_val if cond else false_val in Python since a few years). For & and |, the result type depends on how the operands overload the respective special methods (True & False is False, 99 & 7 is 3, for sets it's unions/intersection...).


But even when e.g. a_boolean & another_boolean would work identically, the right solution is using and - simply because and and or are associated with boolean expression and condition while & and | stand for bit twiddling.






share|improve this answer


























  • Point #3 applies to Ruby, Perl and Javascript as well. It isn't that Python-specific.

    – kennytm
    Oct 2 '10 at 9:22



















14














Here's a further difference, which had me puzzled for a while just now: because & (and other bitwise operators) have a higher precedence than and (and other boolean operators) the following expressions evaluate to different values:



0 < 1 & 0 < 2


versus



0 < 1 and 0 < 2


To wit, the first yields False as it is equivalent to 0 < (1 & 0) < 2, hence 0 < 0 < 2, hence 0 < 0 and 0 < 2.






share|improve this answer































    3














    If you are trying to do element-wise boolean operations in numpy, the answer is somewhat different. You can use & and | for element-wise boolean operations, but and and or will return value error.



    To be on the safe side, you can use the numpy logic functions.



    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)





    share|improve this answer































      2














      Boolean operation are logical operations.



      Bitwise operations are operations on binary bits.



      Bitwise operations:



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


      The operations:



      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


      Some of the uses of bitwise operations:



      1) Setting and Clearing Bits



      Boolean operations:



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





      share|improve this answer


























      • For you boolean operations, don't you mean "and" and "or" instead of "&" and "|"?

        – Matthew Rankin
        Oct 2 '10 at 9:05











      • Yes .. Yes .. Thanks , I do mean that.

        – pyfunc
        Oct 2 '10 at 9:07



















      2














      The hint is in the name:




      • Boolean operators are for performing logical operations (truth testing common in programming and formal logic)

      • 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.






      share|improve this answer

































        1














        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 '&' [duplicate]: 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.






        share|improve this answer

































          0














          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)





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3845018%2fboolean-operators-vs-bitwise-operators%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            8 Answers
            8






            active

            oldest

            votes








            8 Answers
            8






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            52














            Here are a couple of guidelines:




            • Boolean operators are usually used on boolean values but bitwise operators are usually used on integer values.

            • Boolean operators are short-circuiting but bitwise operators are not short-circuiting.


            The short-circuiting behaviour is useful in expressions like this:



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


            This would not work correctly with the bitwise & operator because both sides would always be evaluated, giving AttributeError: 'NoneType' object has no attribute 'foo'. When you use the boolean andoperator the second expression is not evaluated when the first is False. Similarly or does not evaluate the second argument if the first is True.






            share|improve this answer





















            • 10





              Supplementary: In Python &, |, ^ are set operations too.

              – kennytm
              Oct 2 '10 at 9:14






            • 3





              Additional supplementary: in Python, bit-wise will not allow mixed types, but boolean will. e.g. True or "True" is fine (it will return the first truthy value), but True | "True" will throw an exception.

              – Hannele
              Feb 10 '16 at 19:11








            • 4





              @Hannele That has nothing to do with mixed types. Bitwise operations only make sense with integers and any other type will throw an exception. The point here is that Python treats False and True as 0 and 1 respectively: 0 == False and 1 == True are both true.

              – Nuno André
              Jul 30 '16 at 17:53






            • 1





              @NunoAndré True enough, that is a more accurate explanation. Thanks!

              – Hannele
              Aug 9 '16 at 5:48






            • 1





              Thank you! That was educational

              – MaxPY
              May 16 '17 at 17:00
















            52














            Here are a couple of guidelines:




            • Boolean operators are usually used on boolean values but bitwise operators are usually used on integer values.

            • Boolean operators are short-circuiting but bitwise operators are not short-circuiting.


            The short-circuiting behaviour is useful in expressions like this:



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


            This would not work correctly with the bitwise & operator because both sides would always be evaluated, giving AttributeError: 'NoneType' object has no attribute 'foo'. When you use the boolean andoperator the second expression is not evaluated when the first is False. Similarly or does not evaluate the second argument if the first is True.






            share|improve this answer





















            • 10





              Supplementary: In Python &, |, ^ are set operations too.

              – kennytm
              Oct 2 '10 at 9:14






            • 3





              Additional supplementary: in Python, bit-wise will not allow mixed types, but boolean will. e.g. True or "True" is fine (it will return the first truthy value), but True | "True" will throw an exception.

              – Hannele
              Feb 10 '16 at 19:11








            • 4





              @Hannele That has nothing to do with mixed types. Bitwise operations only make sense with integers and any other type will throw an exception. The point here is that Python treats False and True as 0 and 1 respectively: 0 == False and 1 == True are both true.

              – Nuno André
              Jul 30 '16 at 17:53






            • 1





              @NunoAndré True enough, that is a more accurate explanation. Thanks!

              – Hannele
              Aug 9 '16 at 5:48






            • 1





              Thank you! That was educational

              – MaxPY
              May 16 '17 at 17:00














            52












            52








            52







            Here are a couple of guidelines:




            • Boolean operators are usually used on boolean values but bitwise operators are usually used on integer values.

            • Boolean operators are short-circuiting but bitwise operators are not short-circuiting.


            The short-circuiting behaviour is useful in expressions like this:



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


            This would not work correctly with the bitwise & operator because both sides would always be evaluated, giving AttributeError: 'NoneType' object has no attribute 'foo'. When you use the boolean andoperator the second expression is not evaluated when the first is False. Similarly or does not evaluate the second argument if the first is True.






            share|improve this answer















            Here are a couple of guidelines:




            • Boolean operators are usually used on boolean values but bitwise operators are usually used on integer values.

            • Boolean operators are short-circuiting but bitwise operators are not short-circuiting.


            The short-circuiting behaviour is useful in expressions like this:



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


            This would not work correctly with the bitwise & operator because both sides would always be evaluated, giving AttributeError: 'NoneType' object has no attribute 'foo'. When you use the boolean andoperator the second expression is not evaluated when the first is False. Similarly or does not evaluate the second argument if the first is True.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Oct 3 '10 at 7:48

























            answered Oct 2 '10 at 8:56









            Mark ByersMark Byers

            588k12513491338




            588k12513491338








            • 10





              Supplementary: In Python &, |, ^ are set operations too.

              – kennytm
              Oct 2 '10 at 9:14






            • 3





              Additional supplementary: in Python, bit-wise will not allow mixed types, but boolean will. e.g. True or "True" is fine (it will return the first truthy value), but True | "True" will throw an exception.

              – Hannele
              Feb 10 '16 at 19:11








            • 4





              @Hannele That has nothing to do with mixed types. Bitwise operations only make sense with integers and any other type will throw an exception. The point here is that Python treats False and True as 0 and 1 respectively: 0 == False and 1 == True are both true.

              – Nuno André
              Jul 30 '16 at 17:53






            • 1





              @NunoAndré True enough, that is a more accurate explanation. Thanks!

              – Hannele
              Aug 9 '16 at 5:48






            • 1





              Thank you! That was educational

              – MaxPY
              May 16 '17 at 17:00














            • 10





              Supplementary: In Python &, |, ^ are set operations too.

              – kennytm
              Oct 2 '10 at 9:14






            • 3





              Additional supplementary: in Python, bit-wise will not allow mixed types, but boolean will. e.g. True or "True" is fine (it will return the first truthy value), but True | "True" will throw an exception.

              – Hannele
              Feb 10 '16 at 19:11








            • 4





              @Hannele That has nothing to do with mixed types. Bitwise operations only make sense with integers and any other type will throw an exception. The point here is that Python treats False and True as 0 and 1 respectively: 0 == False and 1 == True are both true.

              – Nuno André
              Jul 30 '16 at 17:53






            • 1





              @NunoAndré True enough, that is a more accurate explanation. Thanks!

              – Hannele
              Aug 9 '16 at 5:48






            • 1





              Thank you! That was educational

              – MaxPY
              May 16 '17 at 17:00








            10




            10





            Supplementary: In Python &, |, ^ are set operations too.

            – kennytm
            Oct 2 '10 at 9:14





            Supplementary: In Python &, |, ^ are set operations too.

            – kennytm
            Oct 2 '10 at 9:14




            3




            3





            Additional supplementary: in Python, bit-wise will not allow mixed types, but boolean will. e.g. True or "True" is fine (it will return the first truthy value), but True | "True" will throw an exception.

            – Hannele
            Feb 10 '16 at 19:11







            Additional supplementary: in Python, bit-wise will not allow mixed types, but boolean will. e.g. True or "True" is fine (it will return the first truthy value), but True | "True" will throw an exception.

            – Hannele
            Feb 10 '16 at 19:11






            4




            4





            @Hannele That has nothing to do with mixed types. Bitwise operations only make sense with integers and any other type will throw an exception. The point here is that Python treats False and True as 0 and 1 respectively: 0 == False and 1 == True are both true.

            – Nuno André
            Jul 30 '16 at 17:53





            @Hannele That has nothing to do with mixed types. Bitwise operations only make sense with integers and any other type will throw an exception. The point here is that Python treats False and True as 0 and 1 respectively: 0 == False and 1 == True are both true.

            – Nuno André
            Jul 30 '16 at 17:53




            1




            1





            @NunoAndré True enough, that is a more accurate explanation. Thanks!

            – Hannele
            Aug 9 '16 at 5:48





            @NunoAndré True enough, that is a more accurate explanation. Thanks!

            – Hannele
            Aug 9 '16 at 5:48




            1




            1





            Thank you! That was educational

            – MaxPY
            May 16 '17 at 17:00





            Thank you! That was educational

            – MaxPY
            May 16 '17 at 17:00













            18














            In theory, and and or come straight from boolean logic (and therefore operate on two booleans to produce a boolean), while & and | apply the boolean and/or to the individual bits of integers. There are a lot lot of questions here on how the latter work exactly.



            Here are practical differences that potentially affect your results:





            1. and and or short-circuiting, i.e. True or sys.exit(1) will not exit, because for a certain value (True or ..., False and ...) of the first operand, the second one wouldn't change the result = does not need to be evaluated. But | and & don't short-circuit - True | sys.exit(1) throws you outta the REPL.

            2. (Only applies to some? languages with operator overloading, including Python:) & and | are regular operators and can be overloaded - and and or are forged into the language (although at least in Python, the special method for coercion to boolean may have side effects).

            3. (only applies to a few languages [see KennyTM's comment]:) and and or return (always? never really understand this, nor did I need it) the value of an operand instead of True or False. This doesn't change the meaning of boolean expressions in conditions - 1 or True is 1, but 1 is true, too. But it was once used to emulate a conditional operator (cond ? true_val : false_val in C syntax, true_val if cond else false_val in Python since a few years). For & and |, the result type depends on how the operands overload the respective special methods (True & False is False, 99 & 7 is 3, for sets it's unions/intersection...).


            But even when e.g. a_boolean & another_boolean would work identically, the right solution is using and - simply because and and or are associated with boolean expression and condition while & and | stand for bit twiddling.






            share|improve this answer


























            • Point #3 applies to Ruby, Perl and Javascript as well. It isn't that Python-specific.

              – kennytm
              Oct 2 '10 at 9:22
















            18














            In theory, and and or come straight from boolean logic (and therefore operate on two booleans to produce a boolean), while & and | apply the boolean and/or to the individual bits of integers. There are a lot lot of questions here on how the latter work exactly.



            Here are practical differences that potentially affect your results:





            1. and and or short-circuiting, i.e. True or sys.exit(1) will not exit, because for a certain value (True or ..., False and ...) of the first operand, the second one wouldn't change the result = does not need to be evaluated. But | and & don't short-circuit - True | sys.exit(1) throws you outta the REPL.

            2. (Only applies to some? languages with operator overloading, including Python:) & and | are regular operators and can be overloaded - and and or are forged into the language (although at least in Python, the special method for coercion to boolean may have side effects).

            3. (only applies to a few languages [see KennyTM's comment]:) and and or return (always? never really understand this, nor did I need it) the value of an operand instead of True or False. This doesn't change the meaning of boolean expressions in conditions - 1 or True is 1, but 1 is true, too. But it was once used to emulate a conditional operator (cond ? true_val : false_val in C syntax, true_val if cond else false_val in Python since a few years). For & and |, the result type depends on how the operands overload the respective special methods (True & False is False, 99 & 7 is 3, for sets it's unions/intersection...).


            But even when e.g. a_boolean & another_boolean would work identically, the right solution is using and - simply because and and or are associated with boolean expression and condition while & and | stand for bit twiddling.






            share|improve this answer


























            • Point #3 applies to Ruby, Perl and Javascript as well. It isn't that Python-specific.

              – kennytm
              Oct 2 '10 at 9:22














            18












            18








            18







            In theory, and and or come straight from boolean logic (and therefore operate on two booleans to produce a boolean), while & and | apply the boolean and/or to the individual bits of integers. There are a lot lot of questions here on how the latter work exactly.



            Here are practical differences that potentially affect your results:





            1. and and or short-circuiting, i.e. True or sys.exit(1) will not exit, because for a certain value (True or ..., False and ...) of the first operand, the second one wouldn't change the result = does not need to be evaluated. But | and & don't short-circuit - True | sys.exit(1) throws you outta the REPL.

            2. (Only applies to some? languages with operator overloading, including Python:) & and | are regular operators and can be overloaded - and and or are forged into the language (although at least in Python, the special method for coercion to boolean may have side effects).

            3. (only applies to a few languages [see KennyTM's comment]:) and and or return (always? never really understand this, nor did I need it) the value of an operand instead of True or False. This doesn't change the meaning of boolean expressions in conditions - 1 or True is 1, but 1 is true, too. But it was once used to emulate a conditional operator (cond ? true_val : false_val in C syntax, true_val if cond else false_val in Python since a few years). For & and |, the result type depends on how the operands overload the respective special methods (True & False is False, 99 & 7 is 3, for sets it's unions/intersection...).


            But even when e.g. a_boolean & another_boolean would work identically, the right solution is using and - simply because and and or are associated with boolean expression and condition while & and | stand for bit twiddling.






            share|improve this answer















            In theory, and and or come straight from boolean logic (and therefore operate on two booleans to produce a boolean), while & and | apply the boolean and/or to the individual bits of integers. There are a lot lot of questions here on how the latter work exactly.



            Here are practical differences that potentially affect your results:





            1. and and or short-circuiting, i.e. True or sys.exit(1) will not exit, because for a certain value (True or ..., False and ...) of the first operand, the second one wouldn't change the result = does not need to be evaluated. But | and & don't short-circuit - True | sys.exit(1) throws you outta the REPL.

            2. (Only applies to some? languages with operator overloading, including Python:) & and | are regular operators and can be overloaded - and and or are forged into the language (although at least in Python, the special method for coercion to boolean may have side effects).

            3. (only applies to a few languages [see KennyTM's comment]:) and and or return (always? never really understand this, nor did I need it) the value of an operand instead of True or False. This doesn't change the meaning of boolean expressions in conditions - 1 or True is 1, but 1 is true, too. But it was once used to emulate a conditional operator (cond ? true_val : false_val in C syntax, true_val if cond else false_val in Python since a few years). For & and |, the result type depends on how the operands overload the respective special methods (True & False is False, 99 & 7 is 3, for sets it's unions/intersection...).


            But even when e.g. a_boolean & another_boolean would work identically, the right solution is using and - simply because and and or are associated with boolean expression and condition while & and | stand for bit twiddling.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Oct 3 '10 at 9:53

























            answered Oct 2 '10 at 9:16







            user395760




















            • Point #3 applies to Ruby, Perl and Javascript as well. It isn't that Python-specific.

              – kennytm
              Oct 2 '10 at 9:22



















            • Point #3 applies to Ruby, Perl and Javascript as well. It isn't that Python-specific.

              – kennytm
              Oct 2 '10 at 9:22

















            Point #3 applies to Ruby, Perl and Javascript as well. It isn't that Python-specific.

            – kennytm
            Oct 2 '10 at 9:22





            Point #3 applies to Ruby, Perl and Javascript as well. It isn't that Python-specific.

            – kennytm
            Oct 2 '10 at 9:22











            14














            Here's a further difference, which had me puzzled for a while just now: because & (and other bitwise operators) have a higher precedence than and (and other boolean operators) the following expressions evaluate to different values:



            0 < 1 & 0 < 2


            versus



            0 < 1 and 0 < 2


            To wit, the first yields False as it is equivalent to 0 < (1 & 0) < 2, hence 0 < 0 < 2, hence 0 < 0 and 0 < 2.






            share|improve this answer




























              14














              Here's a further difference, which had me puzzled for a while just now: because & (and other bitwise operators) have a higher precedence than and (and other boolean operators) the following expressions evaluate to different values:



              0 < 1 & 0 < 2


              versus



              0 < 1 and 0 < 2


              To wit, the first yields False as it is equivalent to 0 < (1 & 0) < 2, hence 0 < 0 < 2, hence 0 < 0 and 0 < 2.






              share|improve this answer


























                14












                14








                14







                Here's a further difference, which had me puzzled for a while just now: because & (and other bitwise operators) have a higher precedence than and (and other boolean operators) the following expressions evaluate to different values:



                0 < 1 & 0 < 2


                versus



                0 < 1 and 0 < 2


                To wit, the first yields False as it is equivalent to 0 < (1 & 0) < 2, hence 0 < 0 < 2, hence 0 < 0 and 0 < 2.






                share|improve this answer













                Here's a further difference, which had me puzzled for a while just now: because & (and other bitwise operators) have a higher precedence than and (and other boolean operators) the following expressions evaluate to different values:



                0 < 1 & 0 < 2


                versus



                0 < 1 and 0 < 2


                To wit, the first yields False as it is equivalent to 0 < (1 & 0) < 2, hence 0 < 0 < 2, hence 0 < 0 and 0 < 2.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Sep 20 '14 at 14:07









                ArendArend

                1,6831315




                1,6831315























                    3














                    If you are trying to do element-wise boolean operations in numpy, the answer is somewhat different. You can use & and | for element-wise boolean operations, but and and or will return value error.



                    To be on the safe side, you can use the numpy logic functions.



                    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)





                    share|improve this answer




























                      3














                      If you are trying to do element-wise boolean operations in numpy, the answer is somewhat different. You can use & and | for element-wise boolean operations, but and and or will return value error.



                      To be on the safe side, you can use the numpy logic functions.



                      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)





                      share|improve this answer


























                        3












                        3








                        3







                        If you are trying to do element-wise boolean operations in numpy, the answer is somewhat different. You can use & and | for element-wise boolean operations, but and and or will return value error.



                        To be on the safe side, you can use the numpy logic functions.



                        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)





                        share|improve this answer













                        If you are trying to do element-wise boolean operations in numpy, the answer is somewhat different. You can use & and | for element-wise boolean operations, but and and or will return value error.



                        To be on the safe side, you can use the numpy logic functions.



                        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)






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Aug 3 '16 at 17:13









                        C8H10N4O2C8H10N4O2

                        9,54655082




                        9,54655082























                            2














                            Boolean operation are logical operations.



                            Bitwise operations are operations on binary bits.



                            Bitwise operations:



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


                            The operations:



                            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


                            Some of the uses of bitwise operations:



                            1) Setting and Clearing Bits



                            Boolean operations:



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





                            share|improve this answer


























                            • For you boolean operations, don't you mean "and" and "or" instead of "&" and "|"?

                              – Matthew Rankin
                              Oct 2 '10 at 9:05











                            • Yes .. Yes .. Thanks , I do mean that.

                              – pyfunc
                              Oct 2 '10 at 9:07
















                            2














                            Boolean operation are logical operations.



                            Bitwise operations are operations on binary bits.



                            Bitwise operations:



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


                            The operations:



                            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


                            Some of the uses of bitwise operations:



                            1) Setting and Clearing Bits



                            Boolean operations:



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





                            share|improve this answer


























                            • For you boolean operations, don't you mean "and" and "or" instead of "&" and "|"?

                              – Matthew Rankin
                              Oct 2 '10 at 9:05











                            • Yes .. Yes .. Thanks , I do mean that.

                              – pyfunc
                              Oct 2 '10 at 9:07














                            2












                            2








                            2







                            Boolean operation are logical operations.



                            Bitwise operations are operations on binary bits.



                            Bitwise operations:



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


                            The operations:



                            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


                            Some of the uses of bitwise operations:



                            1) Setting and Clearing Bits



                            Boolean operations:



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





                            share|improve this answer















                            Boolean operation are logical operations.



                            Bitwise operations are operations on binary bits.



                            Bitwise operations:



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


                            The operations:



                            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


                            Some of the uses of bitwise operations:



                            1) Setting and Clearing Bits



                            Boolean operations:



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






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Oct 2 '10 at 9:09

























                            answered Oct 2 '10 at 8:59









                            pyfuncpyfunc

                            52.5k13125127




                            52.5k13125127













                            • For you boolean operations, don't you mean "and" and "or" instead of "&" and "|"?

                              – Matthew Rankin
                              Oct 2 '10 at 9:05











                            • Yes .. Yes .. Thanks , I do mean that.

                              – pyfunc
                              Oct 2 '10 at 9:07



















                            • For you boolean operations, don't you mean "and" and "or" instead of "&" and "|"?

                              – Matthew Rankin
                              Oct 2 '10 at 9:05











                            • Yes .. Yes .. Thanks , I do mean that.

                              – pyfunc
                              Oct 2 '10 at 9:07

















                            For you boolean operations, don't you mean "and" and "or" instead of "&" and "|"?

                            – Matthew Rankin
                            Oct 2 '10 at 9:05





                            For you boolean operations, don't you mean "and" and "or" instead of "&" and "|"?

                            – Matthew Rankin
                            Oct 2 '10 at 9:05













                            Yes .. Yes .. Thanks , I do mean that.

                            – pyfunc
                            Oct 2 '10 at 9:07





                            Yes .. Yes .. Thanks , I do mean that.

                            – pyfunc
                            Oct 2 '10 at 9:07











                            2














                            The hint is in the name:




                            • Boolean operators are for performing logical operations (truth testing common in programming and formal logic)

                            • 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.






                            share|improve this answer






























                              2














                              The hint is in the name:




                              • Boolean operators are for performing logical operations (truth testing common in programming and formal logic)

                              • 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.






                              share|improve this answer




























                                2












                                2








                                2







                                The hint is in the name:




                                • Boolean operators are for performing logical operations (truth testing common in programming and formal logic)

                                • 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.






                                share|improve this answer















                                The hint is in the name:




                                • Boolean operators are for performing logical operations (truth testing common in programming and formal logic)

                                • 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.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Oct 2 '10 at 10:46

























                                answered Oct 2 '10 at 9:08









                                Tendayi MawusheTendayi Mawushe

                                20.5k44052




                                20.5k44052























                                    1














                                    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 '&' [duplicate]: 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.






                                    share|improve this answer






























                                      1














                                      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 '&' [duplicate]: 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.






                                      share|improve this answer




























                                        1












                                        1








                                        1







                                        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 '&' [duplicate]: 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.






                                        share|improve this answer















                                        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 '&' [duplicate]: 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.







                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jan 23 at 18:47

























                                        answered May 21 '18 at 10:15









                                        CristiFatiCristiFati

                                        12.7k72436




                                        12.7k72436























                                            0














                                            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)





                                            share|improve this answer




























                                              0














                                              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)





                                              share|improve this answer


























                                                0












                                                0








                                                0







                                                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)





                                                share|improve this answer













                                                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)






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Sep 26 '17 at 23:21









                                                geoffLangenderfergeoffLangenderfer

                                                1915




                                                1915






























                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3845018%2fboolean-operators-vs-bitwise-operators%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Tonle Sap (See)

                                                    I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

                                                    Guatemaltekische Davis-Cup-Mannschaft