How to wrap a number using the mod operator

Not sure if this is possible, but is there an automatic way using mod or something similar to automatically fix bad input values? For instance:

If r>255, then set r=255 and
if r<0, then set r=0

So basically what I ask is a smart math way to fix this and not use

if(r>255)
 r=255;
if(r<0)
 r=0;
+3
source share
5 answers

What about:

r = std:max(0, std::min(r, 255));
+7
source

The following function displays what you are looking for:

 f(x) = (510*(1 + Sign[-255 + x]) + x*(1 + Sign[255 - x])*(1 + Sign[x]))/4

As below:

enter image description here

+2
source

- :

R = MIN(r, 255);
R = MAX(R, 0);
0

, , , ints, :

, unsigned int - 16 ( ):

r = r & 0000000011111111;

int 32 , 16 -.

r 255. int - . , ( , , ). , r = min(r, 0); .

0

. ( 0 255) :

static inline int trim_8bit(unsigned i){
    return 0xff & ((i | -!!(i & ~0xff))) + (i >> 31);
    // where "0xff &" can be omitted if you return unsigned char
};

,

static inline unsigned char trim_8bit_v2(unsigned i){   
    if (__builtin_expect(i & ~0xFF, 0)) // it for gcc, use __assume for MSVC
        return (i >> 31) - 1; 
    return i;
};

, , .

0

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


All Articles