c++ - Truncate binary number -


this question has answer here:

i truncate every digit after first non 0 digit in binary representation of integer. need simple possible (no function or multiple lines of code).

in example:

// in c++ int int1=7,int2=12,int3=34;   //needs work number 

using sort of operator (maybe bitwise combination?), need these give following values

int1 -> 4 int2 -> 8 int3 -> 32 

truncating in binary thing think of, open ideas.

thanks!

a pretty neat trick can used that:

if ((v & (v - 1)) == 0) {     return v; } v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; v >>= 1; return v; 

the idea "or in" ones below top 1 after decrementing value, , increment value @ end. added shift right @ end standard trick, because original code designed find smallest 2^n greater or equal given value.

edit: added special case 2^n, another trick same list.

here demo on ideone.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -