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

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -