引用自http://graphics.stanford.edu/~seander/bithacks.html,用于在没有分支的情况下计算整数绝对值(abs)的代码:
int v; // we want to find the absolute value of v
unsigned int r; // the result goes here
int const mask = v >> sizeof(int) * CHAR_BIT - 1;
r = (v + mask) ^ mask;
专利变种:
r = (v ^ mask) - mask;
什么是CHAR_BIT
,如何使用它?
v + mask
可能会导致int
溢出 - 这是_未定义的行为_。(v ^ mask) - mask
也可能存在类似的问题。 - chux - Reinstate Monica