Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104702

Turn on leftmost bit of a Short

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.

Upvotes: 0

Views: 419

Answers (2)

dbasnett
dbasnett

Reputation: 11773

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

Upvotes: 1

Billy ONeal
Billy ONeal

Reputation: 106530

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

Upvotes: 3

Related Questions