C:在Xcode中输出正确但不在终端输出

时间:2017-03-29 00:18:04

标签: c xcode bit-manipulation

我正在编写一个输出double的函数,无论传入什么值,但如果它溢出正输出最高可能的整数,如果它溢出负输出最低可能的整数。我们只允许使用带符号的32位整数。我不能使用任何if语句,循环等,也不能使用任何不允许的操作。允许的操作是:! 〜& ^ | +<< >>

以下是在main方法中调用它的方法:

printf("Boundedmult should be 2: %d\n", boundedMult(0x00000001));
printf("Boundedmult should be 2147483647: %d\n", boundedMult(0x50000000));
printf("Boundedmult should be -2147483648: %d\n", boundedMult(0xA0000000));

在Xcode上输出为:

Boundedmult should be 2: 2
Boundedmult should be 2147483647: 2147483647
Boundedmult should be -2147483648: -2147483648

在终端上输出为:

Boundedmult should be 2: 2
Boundedmult should be 2147483647: -1610612735
Boundedmult should be -2147483648: 1073741824

这是boundedMult方法:

int boundedMult(int x) {
    int x2 = x + x;
    int signBitX  = x >> 31;
    int signBitX2 = x2 >> 31;
    //If x=neg,x2=neg : 1   x=pos, x2=pos : 0   If overflowed x=neg, x2=pos : 0     x=pos, x2=neg :0
    int negOverflowCheck = signBitX & signBitX2;
    //If negOverflowCheck != signBitX, then neg overflow
    int negOverflow = negOverflowCheck & signBitX; //1 = no negative overflow

    //If x=neg,x2=neg : 1   x=pos, x2=pos : 0   If overflowed x=neg, x2=pos : 1     x=pos, x2=neg : 1
    int posOverflowCheck = signBitX | signBitX2;
    //If posOverflowCheck | signBitX = 1
    int posOverflow = posOverflowCheck | signBitX; //0 = no negative overflow

    int largeNeg = 1 << 31;
    int largePos = 0xFF;
    largePos = largePos | (largePos << 8) | (largePos << 16) | (largePos << 23);
    //If x is neg and negOverflow = false return result or if negOverflow = true return largest neg
    //Or if x is pos and posOverflow= false return result or if posOverflow = true return largest pos
    //I'm using true and false as in matching the comments above not C convention so for negOveflow 1 = false (no overflow) and for posOverflow 0 = false (no overflow)
    return ((~!!signBitX+1)&((~negOverflow & largeNeg)|(negOverflow & x2))) | ((~!signBitX+1)&((~posOverflow & x2)|(posOverflow & largePos)));
}

我将不胜感激任何帮助!谢谢!

编辑:我在终端

中使用gcc编译器

0 个答案:

没有答案