饱和加用C [英] Saturating Addition in C
本文介绍了饱和加用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是最好的(最清洁,最高效的)的方式来写饱和除了用C?
What is the best (cleanest, most efficient) way to write saturating addition in C?
函数或宏应该增加两个无符号的输入(需要16位和32位版本),并返回所有位一体(0xFFFF或0xFFFFFFFF的),如果和溢出。
The function or macro should add two unsigned inputs (need both 16- and 32-bit versions) and return all-bits-one (0xFFFF or 0xFFFFFFFF) if the sum overflows.
目标是x86和ARM使用gcc(4.1.2)和Visual Studio(模拟而已,所以一个候补执行正常那里)。
Target is x86 and ARM using gcc (4.1.2) and Visual Studio (for simulation only, so a fallback implementation is OK there).
推荐答案
在普通的C:
uint16_t sadd16(uint16_t a, uint16_t b)
{ return (a > 0xFFFF - b) ? 0xFFFF : a + b; }
uint32_t sadd32(uint32_t a, uint32_t b)
{ return (a > 0xFFFFFFFF - b) ? 0xFFFFFFFF : a + b;}
这几乎是宏观源化和直接传达的意思。
which is almost macro-ized and directly conveys the meaning.
这篇关于饱和加用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文