Rover12421's Blog

The End.

判断整数的符号性质

#include <stdio.h>
#include <LIMITS.H>

/
    判断整数的符号性质
*/
int compute_int_sign(int v)
{
    int sign;

    //v = 0xFFFFFFFF;
    //v = 0;
    //v = 0x7FFFFFFF;

    //method 1
    //最简单的直接用v和0比较
    //负数sign=-1,非负数sign=0
    sign = -(v < );
    printf(“1:sign<%d>\n, sign);

    //method 2
    //先把v强制成无符号型后移位只保留v的符号位,移位后转成int型再取反
    //由于无符号型移位都是补0,移植性很强
    //负数sign=-1,非负数sign=0
    sign = -(int)((unsigned int)((int)v) >> (sizeof(int) * CHAR_BIT - 1));
    printf(“2:sign<%d>\n, sign);

    //method 3
    //直接移位只保留v的符号位,移植性没上一个好
    //负数sign=-1,非负数sign=0
    sign = v >> (sizeof(int) * CHAR_BIT - 1);
    printf(“3:sign<%d>\n, sign);

    //method 4
    //同method 3
    //把结果|上了1,改变了结果使得:
    //负数sign=-1,非负数sign=1
    sign = +1 | (v >> (sizeof(int) * CHAR_BIT - 1));
    printf(“4:sign<%d>\n, sign);

    //method 5
    //|之后的内容同 method 2 一样
    //|(v != 0)只是为了改变v>=0时的结果
    //v>0, 1|0 = 1
    //v=0, 0|0 = 0
    //所以改变结果后:
    //v大于0,sign=1
    //v等于0,sign=0
    //v小于0,sign=-1
    sign = (v != ) | -(int)((unsigned int)((int)v) >> (sizeof(int) * CHAR_BIT - 1));
    printf(“5:sign<%d>\n, sign);

    //method 6
    //|之后的内容同 method 3 一样
    //|(v != 0)同 method 5
    //v大于0,sign=1
    //v等于0,sign=0
    //v小于0,sign=-1
    sign = (v != ) | (v >> (sizeof(int) * CHAR_BIT - 1));
    printf(“6:sign<%d>\n, sign);

    //method 7
    //v大于0,sign=1-0=1
    //v等于0,sign=0-0=0
    //v小于0,sign=0-1=-1
    sign = (v > ) - (v < );
    printf(“7:sign<%d>\n, sign);

    return sign;
}

Comments