How to make it so that when subtracting 2 numbers uint32_t , when we subtract more from the smaller one, the result is 0?
Without if, and preferably without comparison operators
How to make it so that when subtracting 2 numbers uint32_t , when we subtract more from the smaller one, the result is 0?
Without if, and preferably without comparison operators
"Well, the tasks you, sir, put ..." (c) C / f "Formula of love"
There is one catch - a sign shift is required, and so that it works correctly, spreading the sign. The trouble is that formally it is implementation defined, although in most implementations it works correctly.
If so, then you can implement the desired "monus", it is also dozu(x,y) you can:
(xy)&~(int((~x&y)|((~(x^y))&(xy)))>>31) Read Warren G. Algorithmic tricks for programmers , the book is worth it :)
u32b sat_subu32b(u32b x, u32b y) { u32b res = x - y; res &= -(res <= x); return res; } Peeped here .
The simplest solution would be the following:
auto sum = first > second ? first - second : 0; There are no ifs, but there is an "undesirable" comparison operator. Well, it is undesirable, but not prohibited.
You can make another solution to meet the requirements:
bool div = first / second; auto sum = (first - second)*div; No ifs, no comparisons. The decision is terrible. Like the requirements.
Source: https://ru.stackoverflow.com/questions/507964/
All Articles