How does this min () function work?

I came across this code:

int __min(int a, int b) { return ((a)-(((a)-(b))&((b)-(a))>>31)); } 

I can imagine that it has something to do with 2s complement and that it only works for signed 32-bit integers, but after that I am lost.

I found this question , but I donโ€™t think the functions are related, or am I wrong?

I have 2 questions:

  • Why does this feature work?
  • Is there a situation where (a<b)?a:b does not work, and this function would be, or is this function simply complicated for fun?

EDIT: The function is written for the GPU, so I think @Banex might be right about writing in such a way as to avoid branching.

+5
source share
2 answers

It is designed to work with 32-bit characters. Let me break it down one step at a time.

 ((b)-(a))>>31) 

The right-shift operator essentially takes the most significant bit in a 32-bit value, and the sign expands it to the remaining 31 bits. This is how the shift shift operator works for signed values.

If b greater than a , the subtraction result will be positive, the most significant bit will be 0, and the result will be 0.

If b less than a , the result of the subtraction will be negative, the most significant bit will be 1, and the result will be -1. The most significant bit is reset to all remaining bits. All bits in a 32-bit value will be set, which is -1.

You can verify this yourself by writing a short program that puts a positive or negative value in a 32-bit int , moves right 31 bits; then, noticing that the result will be either 0 or -1. As you know, in arithmetic with two additions, the value -1 has all its bits.

 ((a)-(b)) & (0 or -1, as the result of the previous operation). 

So, if b less than a , the right side value has all the set bits, and the result of the bitwise & operator is the left side value. or ab .

If b greater than a , the value of the right side has all bits 0, and the result & is 0.

Finally:

If b less than a , the expression above:

 a-(ab) or a-a+b or b 

And if b greater than a , the result of the expression

 a - 0 or a 
+2
source

Expression

 ((a)-(b))&((b)-(a))>>31 

i.e. without the extra bracket

 (a - b) & (b - a) >> 31 

estimated as

 a - b 

if a> b and <

 0 

otherwise, therefore, if it is finally subtracted from a, it will be the same as

 if (a > b) return (a - (a - b)); else return (a - 0); 
0
source

Source: https://habr.com/ru/post/1258973/


All Articles