/* Hi,
In my process of C code optimization*/
Clip(int Val)
{
return (curr < 0 ? : ((curr > 255) ? 255 : curr));
}
/* I want the int value to be clipped between 0 to 255.
Is there any other way to optimize above code snippet? */
Falcon143
0
Newbie Poster
Recommended Answers
Jump to PostI assume you are missing a 0 between the first
? :
.You could use the modulous (%) operator rather than a second test. Whether this is better rather depends on the processor it is running on though
Clip(int Val) { return ((curr < 0) ? …
Jump to PostNot sure about optimal but here's a way using included functions, rather than chained conditionals:
#include <iostream> #include <cmath> using namespace std; int Clip(int Val) { return fmin(fmax(Val,0.0),255.0); } int main() { int test; test = 100; cout << Clip(test); return 0; }
Jump to Postint Clip(int Val) { return (Val < 0 ? 0 : (Val > 0xFF ? 0xFF : Val & 0xFF)); }
My simple contribution.
All 10 Replies
Banfa
597
Posting Pro
Featured Poster
tinstaafl
1,176
Posting Maven
L7Sqr
227
Practically a Master Poster
Banfa
597
Posting Pro
Featured Poster
L7Sqr
227
Practically a Master Poster
tinstaafl
1,176
Posting Maven
Falcon143
0
Newbie Poster
tinstaafl
1,176
Posting Maven
nullptr
167
Occasional Poster
rubberman
commented:
Just what I was going to post! :-)
+12
Banfa
597
Posting Pro
Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.