#### Archived

This topic is now archived and is closed to further replies.

# What's your fastest algorithm for clipping char + char to 255?

This topic is 6126 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Well, I don''t have one. The one I''m using stores the sum as an int and compares the sum to 255, clipping if it''s greater. That''s pretty pokey, I''d bet. I''ve seen people use humongous bit manipulation statements, statements that span like 4 lines, and claim it''s faster than just a compare. I''ve not tried out those methods, but I can''t see how 5 or 6 shifts and masks are faster than a single compare. Well, anyway, I''ve curious to see what you guys have seen, done, or can come up with. Thank you for your bandwidth, -- Succinct

##### Share on other sites
Umm, is this what you are looking for?

c = (a + b) & 0xFF;

-Brannon

##### Share on other sites
Not exactly.

That will only keep the portion of the sum that is less than 255. Doing it that way, if a and b are 128, c will be 0.

Ok - my last post must've been too vague:
int iSum = c1 + c2;
return char( (iSum < 255) ? iSum : 255 );

Anyone have a better way of expressing this, maybe even using assembly?

-- Succinct

Edited by - Succinct on December 15, 2001 12:58:13 PM

##### Share on other sites
Your solution works fine in the average case (the case when roughly half the values need to be clipped). In the worst case (when nearly all values need to be clipped) you can get slightly better performance by using bit manipulations to clip without doing the comparison. This works better in the worst case because even though there may be more instructions, you avoid the branch misprediction (which would happen on most passes). However, if this isn''t a critical speed section of your code, I would stick with the version you have

##### Share on other sites
Well, it''s the inner loop of a software blitter .

I''ve seen the bit manipulations. It didn''t occur to me that, due to branch predictions and the possibility of missing one using a compare, that they would be faster.

Thank''s lots, AP, it looks like I''ll be adding them now.

Anyone else have any suggestions?

##### Share on other sites
yes..
use MMX asm instructions. It has been a long time since I tried it so I don''t remember the name of the function, but it takes two 32 bits registers and clamp every 8 bits value to 255.

1. 1
2. 2
3. 3
Rutin
18
4. 4
JoeJ
14
5. 5

• 14
• 10
• 23
• 9
• 36
• ### Forum Statistics

• Total Topics
632634
• Total Posts
3007551
• ### Who's Online (See full list)

There are no registered users currently online

×