這裏有一個相當簡潔的表達,這將解決這個問題它不工作:
return ((x < 0^y) & x!=0) << 31 | (x!=0) <<31>> 31 & 0x7fffffff & x | x==0x80000000 ;
這將適用於32位2的補碼整數,其中x是輸入,y是1或0. 1表示返回x的相反符號,0表示返回與x相同的符號。
這是函數f()中該表達式的更長版本。我已經添加了一些測試用例來驗證。
#include <limits.h>
#include <stdio.h>
int bitsm1 = 31;
int rightbits = 0x7fffffff;
int f (x, y) {
int sign_x = x < 0;
int signtemp = sign_x^y;
int notzero = x!=0;
int v = notzero << bitsm1;
v = v >> bitsm1;
v = v & rightbits;
int b = v & x;
int c = (signtemp & notzero) << bitsm1;
int z = c | b;
int res = z | (x==INT_MIN);
return res;
}
int main() {
printf("%d\n", f(0,0)); // 0
printf("%d\n", f(0,1)); // 0
printf("%d\n", f(1,0)); // +
printf("%d\n", f(1,1)); // -
printf("%d\n", f(-1,0)); // -
printf("%d\n", f(-1,1)); // +
printf("%d\n", f(INT_MAX,0)); // +
printf("%d\n", f(INT_MAX,1)); // -
printf("%d\n", f(INT_MIN,0)); // -
printf("%d\n", f(INT_MIN,1)); // +
return 0;
}
整數或浮點數? – 2011-02-01 18:57:24