Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Detecting whether UV fits into an NV

by stevieb (Canon)
on Feb 26, 2020 at 01:45 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11113420]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-03-28 13:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found