Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get 1, 0, -1 as positive, zero, or negative for an integer with math only

Tags:

algorithm

I have a situation where I'm performing a calculate over a huge number of rows, and I can really increase the performance if I can eschew a conditional statement.

What I need is for a given positive, zero, or negative integer I want the result 1, 0, -1 respectively.

So if I do col/ABS(col), I will get 1 for a positive number, and -1 for a negative number, but of course if col equals 0 then I'll get an error. I can't get an error.

This seems simple enough, but I can't wrap my ahead around it.

like image 684
Daniel Gimenez Avatar asked Jan 30 '26 21:01

Daniel Gimenez


1 Answers

Assuming either two's complement 32-bit integers, or one's complement with no negative-zero to worry about, then the following works well:

(x>>31) - (-x>>31);

Replace 31 with 63 for 64-bit integers, and so on.

like image 184
Jon Hanna Avatar answered Feb 01 '26 13:02

Jon Hanna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!