打开短片最左边的位

发布于 2024-09-08 06:37:37 字数 339 浏览 0 评论 0原文

原始问题已更改。

我想按位关闭 Short 值 (&H8000) 的最左边位,并保留其他位不变。

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

按位运算符有没有更短的方法?

当我这样做时,

Dim a = Short.MaxValue Or &H8000

我收到编译器错误,因为它会上升,而不是否定它。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你曾走过我的故事 2024-09-15 06:37:38

这是因为 .NET 使用二进制补码,而不是带符号的大小。要求反,您必须翻转所有位,然后添加一位。

仅使用一元减号。拜托...非常拜托。

编辑:如果出于某种奇怪的原因,您必须使用按位运算来执行此操作,则必须执行以下操作:

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

这当然仍然不是按位,因为不能使用按位运算符有效地完成二进制补数否定。

编辑2:这是一个一元减号:

Dim correct = -Short.MaxValue;

编辑3:回应已编辑的问题

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

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
缘字诀 2024-09-15 06:37:38

二进制补码

Dim testV As Short = &HD555S 'a test value

Dim twosC As Short 'twos comp

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

更改最高有效位

twosC = twosC Xor &H8000S

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文