C # how to check the same sign of 2 decimal values โ€‹โ€‹using bits?

I have 2 decimal values: a and b. How to use a bit operator to check if two values โ€‹โ€‹are the same sign?

+7
source share
5 answers

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

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

Do you mean if both are positive or both are negative?

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

You can do,

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

and do

 a.Sign == b.Sign; 
+1
source

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

First, you can use Decimal.GetBits() to get all the bits in two Decimals for comparison, like an array of 4 integers.

Then you can check the sign bit, which is at bit 31 in int with offset 3 in the ints array.

 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)); 
+1
source

To check the sign, you must perform a bit shift:

 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 */ } 

The problem is that you cannot reset the decimal bit. You would need to do something like this:

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

I cannot verify this, but I suspect that this will defeat the goal of optimization using bitwise operators. You can use the built-in Math.Sign() directly.

0
source

All Articles