我正在处理一个任务,但是我不知道如何实现它。我需要创建一个函数sadd(int x, int y)
,它返回两个数字的和,除非它们相加会导致溢出(这时只需返回最大可能的int)。我已经想出了一些解决方案,涉及类型转换和条件语句,但是这些在解决方案中是不允许的。只能使用运算符~ ! ^ + << >> &
和|
。
我正在处理一个任务,但是我不知道如何实现它。我需要创建一个函数sadd(int x, int y)
,它返回两个数字的和,除非它们相加会导致溢出(这时只需返回最大可能的int)。我已经想出了一些解决方案,涉及类型转换和条件语句,但是这些在解决方案中是不允许的。只能使用运算符~ ! ^ + << >> &
和|
。
以下为ARM官网 (ARM信息中心) 有关内置函数的内容:
4.1 Compiler intrinsics
Compiler intrinsics are functions provided by the compiler. They enable you to easily incorporate domain-specific operations in C and C++ source code without resorting to complex implementations in assembly language.
The C and C++ languages are suited to a wide variety of tasks but they do not provide in-built support for specific areas of application, for example, Digital Signal Processing (DSP). Within a given application domain, there is usually a range of domain-specific operations that have to be performed frequently. However, often these operations cannot be efficiently implemented in C or C++. A typical example is the saturated add of two 32-bit signed two’s complement integers, commonly used in DSP programming. The following example shows a C implementation of saturated add operation
#include <limits.h> int L_add(const int a, const int b) { int c; c = a + b; // Needs to be c = a + (unsigned)b; to avoid UB if (((a ^ b) & INT_MIN) == 0) { if ((c ^ a) & INT_MIN) { c = (a < 0) ? INT_MIN : INT_MAX; } } return c; }
在ISO C中,这个例子是不安全的;因为有符号整数溢出是未定义行为,所以你需要避免在检测它时引起它。使用c = a + (unsigned)b;
可以避免这个问题,得到预期的二进制整数结果,因为2的补码加法与无符号二进制相同,但在C中unsigned
类型具有明确定义的包装。
c = a + b;
就会出现未定义行为。在补码机器上,使用 c = a + (unsigned)b;
作为无符号数进行加法运算,然后再隐式转换回带符号数。这是与二进制补码有符号加法相同的操作,但在 C 中保证可以包装。 - Peter Cordes
if
/else
,这将会很麻烦.. - Brendan Long