c - Set or Reset a given bit without branching -
in 1 interview, asked me, how set or reset bit? simple question , answered that.
after asked me, without branching
. dont know branching. search , came here http://graphics.stanford.edu/~seander/bithacks.html
but still not getting concept of branching , non-branching. please explain branching
.
branching means instructions cpu executes contain conditional jump. either-or choice. mean if
, for
-loop, while
-loop, switch
, ?:
or makes decision based on boolean.
one class of branches people forget short-circuiting boolean operators , possibly (but not on cpus) things evaluate truth values, int foo; ...; foo = !foo;
branch on cpus, not (not on x86).
so set bit:
i |= (1 << bit);
reset bit:
i &= ~(1 << bit);
toggle bit:
i ^= (1 << bit);
no branches. don't see how make complicated have use branch.
the reason why might want worry branches branch prediction. see question , answer excellent explanation of why matters.
Comments
Post a Comment