1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Bit operations conditional

  1. Jan 24, 2010 #1
    1. The problem statement, all variables and given/known data

    I want to write the following if statement into simply manipulations using the bit operations: ! ^ & | << >> ~ +

    Given an x...

    if ( x == -1 || x == 0)
    return -1;
    return 0;

    I am dealing with 32-bit integers. How do I go about doing this? (Note: -1 is represented by all 1s and 0 is represented by all 0s. 0b111...111 = -1 and 0b000...000 = 0

    3. The attempt at a solution

    My attempt:

    (-1 & something) | 0

    In other words, I am trying to return -1 on one branch and 0 on the other branch. The "something" needs to determine whether or not x is -1 or 0.

    If I do (-1 | x), it will return -1 when x is either -1 or 0 which is good but it does NOT return 0 when x is anything else. In fact, it always returns -1....
    Last edited: Jan 24, 2010
  2. jcsd
  3. Jan 25, 2010 #2
    What language are you using, and what are these operarators you've introduced? Is | a different operator than || ?
  4. Jan 25, 2010 #3
    Actually, never mind. I figured it out. Thanks anyways.
  5. Jan 25, 2010 #4


    Staff: Mentor

    The language appears to be C or C++. The operators | and || are different, with the first being the bitwise OR operator and the second being the logical OR operator. There are also different operators for AND. The & operator is bitwise AND, while && is the logical AND operator.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook