c++ - Nice way to truncate an integer -


i have function given buffer accepts filled size_t length; however, actual call fills wants int max length.

so, in case parameter cannot fit in integer, want truncated maximum value can fit; couldn't more data anyway.

i can this

int truncatedmaxlen = static_cast<int>(std::min<std::size_t>(maxlength, (std::numeric_limits<int>::max)())); 

any less ugly ways?

a branchless way be:

int truncatedmaxlen = maxlength; truncatedmaxlen |= (truncatedmaxlen < maxlength) * std::numeric_limits<int>::max(); 

for unsigned types nicer because there no sign bit take care of:

unsigned truncatedmaxlen = maxlength; truncatedmaxlen |= -(truncatedmaxlen < maxlength); 

Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -