Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Detecting whether UV fits into an NV

by stevieb (Canon)
on Feb 26, 2020 at 01:45 UTC ( #11113420=note: print w/replies, xml ) Need Help??


in reply to Detecting whether UV fits into an NV

"It annoys me that I can't find a way to detect and shift all of the trailing zero bits off in one hit - and that I instead have to detect and shift them off one at a time. "

Depending what platform you're on, check if the __builtin_ctz() function is available to you. The ctz stands for 'count trailing zeros'. Use this to get the number of trailing zeros, then shift them all off at once.

Update: I've added in bitCount(), which allows you to send in the number after stripping off the trailing zeros, and returns a count of the remaining bits.

#include <stdio.h> #include <math.h> unsigned int bitCount(int num); void main () { /* Here's your example number, in binary format for visual purpose +s */ int num = 0b10100000; int noTrailingZeros = num >> __builtin_ctz(num); unsigned int bitsRemain = bitCount(noTrailingZeros); printf( "Zeros: %d, No Zeros: %d, Bits remain: %d\n", num, noTrailingZeros, bitsRemain ); } unsigned int bitCount(int num) { unsigned int bits = 0; while (num) { bits++; num >>= 1; } return bits; }

Output:

Zeros: 640, No Zeros: 5, Bits remain: 3

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11113420]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2020-03-30 17:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    To "Disagree to disagree" means to:









    Results (175 votes). Check out past polls.

    Notices?