简体   繁体   中英

C# how to check same sign of 2 decimal values using bit?

I have 2 decimal values: a and b. How do I use bit operator to check if two value is same sign?

You can use Math.Sign() . When you use Math.Sign(x) , if x is negative it returns -1 else if its positive, the function returns 1 or when its 0 it returns 0 . So :

if(Math.Sign(a) == Math.Sign(b))
{
    // Code when sign matched.
}
else
{
    // Code when sign not matched.
}

你的意思是两者都是积极的,还是两者都是消极的?

bool bothSameSign = (d1 >= 0 && d2 >= 0) || (d1 < 0 && d2 < 0);

You could make,

static int Sign(this decimal value)
{
    return Decimal.GetBits(value)[3] & 0x8000;
}

and do

a.Sign == b.Sign;

I don't think you really need to use the bit operator for this, but if for some reason you must (eg this is a school question):

Firstly you can use Decimal.GetBits() get all the bits in the two Decimals to compare, as an array of 4 ints.

Then you can inspect the sign bit which is at bit 31 in the int at offset 3 in the array of ints.

Decimal d1 = 1;
Decimal d2 = -1;

var bits1 = Decimal.GetBits(d1);
var bits2 = Decimal.GetBits(d2);

const int signMask = 1 << 31;
const int signWord = 3;

bool sameSign = ((bits1[signWord] & signMask) == (bits2[signWord] & signMask));

Bitwise shift is required for the sign-checking you want to accomplish:

if ( ( number >> sizeof(byte) * sizeof(numberType) -1 ) & 1)
{ /* < 0 */ }
else
{ /* >= 0 */ }

// you can of course use magic numbers 
// example for int: if ( ( number >> 31 ) & 1) { /* < 0 */ }

Problem is, you can't bitshift a decimal . You would have to do something like this:

var shiftableNumber = Int.Parse(Math.Truncate(yourDecimal));

I can't verify it, but I suspect it would defeat the purpose of optimizing through bitwise operators. You might aswell use the builtin Math.Sign() directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM