c++ - Truncate binary number -
this question has answer here:
- getting leftmost bit 9 answers
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
Post a Comment