in reply to Which bit is set? (inverse of (1<<$value) operator)

  1. If only 1-bit will ever be set:

    Use a lookup table:

    %lookup = map{ 2**$_ => $_ } 0 .. 63;; $flags = 0;; $flags |= 1<<(rand 64);; print "The flag set is:", $lookup{ $flags };; The flag set is: 12
  2. If multiple flags can be set:

    Some form of loop is necessary to avoid an impossibly large lookup table:

    $flags = int rand( 2**64 );; print for grep $flags & 1 << $_, 0 .. 63;; 49 50 51 54 55 57 58 59 printf "%u\n", $flags;; 1066790161733386240 $t = 0; print $t += 1<<$_ for grep $flags & 1 << $_, 0 .. 63;; 562949953421312 1688849860263936 3940649673949184 21955048183431168 57983845202395136 202099033278251008 490329409429962752 1066790161733386240

With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

RIP Neil Armstrong

Replies are listed 'Best First'.
Re^2: Which bit is set? (inverse of (1<<$value) operator)
by wirito (Acolyte) on Sep 17, 2012 at 12:11 UTC

    Many thanks!

    The lookup idea is nice and clean. I will use it as I only have 9 different bits.

    However, your second option is the one I was (foolish) looking for. In my code, this could be the line:

    # return the first less significant bit set. return $_ for grep { $bit & 1<<$_ } (0..8)';