Reputation: 25840
How do I eliminate the ternary operator from the code below? I'm looking for something using only integer operators (shifts, additions, etc).
a = (a < 0) ? (-a * 2) - 1 : (a * 2)
Upvotes: 1
Views: 300
Reputation: 59553
It should be something like this:
a = ((a ^ (a >> 31)) + 1) * 2 - ~(a >>> 31) - 1;
(I haven’t actually tried it, though—not being a Java programmer.)
Upvotes: 0
Reputation: 75426
if (a < 0)
a = (-a * 2) - 1
else
a = (a * 2)
Upvotes: 2
Reputation: 1075785
What you have is several answers demonstrating that getting rid of the ternary is not a good idea. It means your code is hard to read, hard to debug, hard to maintain. You haven't flagged this as homework or an intellectual exercise, and so the right answer is: Don't. Leave the ternary in place. It's clear, it's expressive, and it does the job.
Upvotes: 3
Reputation: 147164
Off the top of my head, assuming a
is an int
:
a = 2*a*(1+2*(a>>31)) - (a>>>31);
>>
is arithmetic (signed) shift left. So a>>31
replaces all the bits with the sign bit. All bits set gives -1. Multiple by two and add one, negatives go to -1 and positives (and zero) to 1.
>>>
is logical (unsigned) shift left. So a>>>31
clears the top 31 bits and places the sign bit in bit 0 (0 for positive numbers and zero; 1 for negative numbers).
The "proper" way of doing something vaguely like this is:
a ^= a>>31;
a *= 2;
Upvotes: 7