Search code examples
vb.netbit-manipulationbitwise-operatorsnegationnegate

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.


Solution

  • 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