Bitwise operations in C #

Is there a shorter and more beautiful alternative

(b == 0) ? 0 : 1;

in terms of bitwise operations?

Also, to get the correct sign (-1, 0, or 1) of a given integer a, I currently use

(a > 0) ? 1 : (a >> 32);

Are there any shorter (but not slower) paths?

+3
source share
3 answers

Personally, I stick to the first option for the option "equal to zero or not."

For the integer sign, I would use Math.Sign and suggested that the JIT compiler is going to embed it - testing this assumption with benchmarks if it turns out to be a potential bottleneck.

, - . - . , ... , 5 , , Int32 (int).

EDIT: , , :

int y = x > 0 ? 1 : x;

.

-, .   , . , , .

+6

. .

+4

... Can -, , ? , (-1, 0 1) a

(a > 0) ? 1 : (a >> 32); 

, , , , .

, 32- 32, 33- , 2- .

, 32- . , . . , , (-1,0,1), , . 1, , , . , .NET Framework, 2 1 . , , , 2 ( ).

I must add that there is only one value for zero when you have a signed integer. I think this was my main problem with your "check sign" expression that you made, which shows a misconception about binary numbers.

http://en.wikipedia.org/wiki/Signed_magnitude#Sign-and-magnitude

+1
source

Source: https://habr.com/ru/post/1794148/


All Articles