Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Bit Operation Counting

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

    I am wondering is there a way to count the number of bits to the left or right of a given 1 in a 32-bit integer?

    For example, if I give the function the number 32 = 0b100000, there are 5 bits to the right of the 1 and hence, 26 bits to the left of the 1.

    The catch is, is there a way to do this by simply using bit operations? i.e. no loops or conditionals? Bit operations include: & ^ | << >> ! and ~

    (Note: I am coding this in C)

    3. The attempt at a solution

    Obviously, if I subtract 1 from the original number, I get all 1s to the right of the original number but I'm still stumped as to how I can count the actual number of bits without using loops or conditional statements.
     
  2. jcsd
  3. Jan 23, 2010 #2

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

  4. Jan 23, 2010 #3
    Thanks, but the link you posted has the solution using a for loop.

    Is there a way to do this without using loops or conditional statements? Simply using bit operations such as << >> ! ~ & | ^
     
  5. Jan 24, 2010 #4

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    Not the kernighan solution - but the ones below it (that was the only entry that had an index position)
     
  6. Jan 24, 2010 #5

    Mark44

    Staff: Mentor

    Read on in the page that mgb_phys linked to. The very first routine uses a for loop, but there are other techniques on the page that don't use loops.
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook