c# - Looking for a more efficient pop count given a restriction -


the popcount function returns number of 1's in input. 0010 1101 has popcount of 4.

currently, using algorithm popcount:

private int popcount(int x) {     x = x - ((x >> 1) & 0x55555555);     x = (x & 0x33333333) + ((x >> 2) & 0x33333333);     return (((x + (x >> 4)) & 0x0f0f0f0f) * 0x01010101) >> 24; } 

this works fine , reason ask more because operation run awfully , looking additional performance gains.

i'm looking way simplify algorithm based on fact 1's right aligned. is, input 00000 11111 (returns 5) or 00000 11111 11111 (returns 10).

is there way make more efficient popcount based on constraint? if input 01011 11101 10011, return 2 because cares right-most ones. seems kind of looping slower existing solution.

here's c# implementation performs "find highest set" (binary logarithm). may or may not faster current popcount, surely slower using real clz and/or popcnt cpu instructions:

static int findmsb( uint input ) {     if (input == 0) return 0;     return (int)(bitconverter.doubletoint64bits(input) >> 52) - 1022; } 

test: http://rextester.com/aoxd85351

and slight variation without conditional branch:

/* precondition: ones right-justified, e.g. 00000111 or 00111111 */ static int findmsb( uint input ) {     return (int)(input & (int)(bitconverter.doubletoint64bits(input) >> 52) - 1022); } 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -