开发者

Turn on leftmost bit of a Short

开发者 https://www.devze.com 2023-01-06 14:08 出处:网络
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.

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开发者_StackOverflow 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
0

精彩评论

暂无评论...
验证码 换一张
取 消