문제

Original question changed.

I want to bitwise turn off the left most bit of a Short value (&H8000) and leave the other bits as they are.

Dim x = BitConverter.GetBytes(Short.MaxValue Or &H8000)
Dim z = BitConverter.ToInt16(x, 0)

Isn't there any shorter way with bitwise operators?

When I do

Dim a = Short.MaxValue Or &H8000

I get a compiler error, cuz it goes up, instead of negating it.

도움이 되었습니까?

해결책

That's because .NET uses two's complement, not signed magnitude. To negate, you have to flip all the bits and then add one.

Please just use the unary minus. Please...Pretty please.

EDIT: If for some strange reason you had to do this with bitwise operations, you would have to do this:

Dim somewhatCorrect = (Short.MaxValue xor Short.MinValue) + 1;

which of course is still not bitwise because two's complement negation cannot be done efficiently with bitwise operators.

EDIT2: And here's an unary minus:

Dim correct = -Short.MaxValue;

EDIT3: In response to edited question:

Dim x As Short = 42
Dim xWithHighBitOn = x Or Short.MinValue

다른 팁

Two's complement

Dim testV As Short = &HD555S 'a test value

Dim twosC As Short 'twos comp

twosC = (testV Xor &HFFFFS) + 1S 'reverse the bits, add 1

Change most significant bit

twosC = twosC Xor &H8000S
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top