Conditionally negate a value without branching

In this post, we will see how to conditionally negate a value without branching.

 

The expression ((flag^(flag-1))*n) negate n when the flag is false and the expression
((n^-flag)+flag) negate n when the flag is true.

 

How does it work?

 

1. For (flag ^ (flag – 1)) * n

if flag = 0, (0 ^ (-1)) * n = -n
if flag = 1, (1 ^ (0)) * n = n

C++

Download   Run Code

Output:

Don’t Negate 2
Negate -2

 

2. For (n ^ -flag) + flag

if flag = 0, (n ^ 0) + 0 = n
if flag = 1, (n ^ -1) + 1 = ~n + 1 = -n (2’s complement notation)

C++

Download   Run Code

Output:

Don’t Negate 2
Negate -2

 
Read More –

Bit Hacks – Part 1 (Basic)
Bit Hacks – Part 2 (Playing with k’th bit)
Bit Hacks – Part 3 (Playing with rightmost set bit of a number)
Bit Hacks – Part 4 (Playing with letters of English alphabet)
Bit Hacks – Part 5 (Find absolute value of an integer without branching)

 
Suggested Read: https://graphics.stanford.edu/~seander/bithacks.html
 

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

 
Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of