【问题标题】:C# NOT (~) bit wise operator returns negative valuesC# NOT (~) 位运算符返回负值
【发布时间】:2016-06-17 12:25:07
【问题描述】:

为什么 C# 的按位 NOT 运算符返回 (the_number*-1)-1

byte a = 1;
Console.WriteLine(~a); //equals -2
byte b = 9;
Console.WriteLine(~b); //equals -10
// Shouldn't a=0 and b=6?

我将如何在 C# 中执行此操作?

9 = 0b1001 -> NOT
  = 0b0110 = 6

【问题讨论】:

标签: c# bitwise-operators bit


【解决方案1】:

按位运算返回int(有符号)类型的值。有符号整数使用two's-complement 表示负数。从字节到整数时使用符号扩展。

byte a = 1; // 0b00000001
int notA = ~a; // 0b11111110 = -128 + 64 + 32 + 16 + 8 + 4 + 2 = -2 (actually 0b11111111 11111111 11111111 11111110)

byte b = 9; // 0b00001001
int notB = ~9; // 0b11110110 = -128 + 64 + 32 + 16 + 4 + 2 = -10 (actually 0b11111111 11111111 11111111 11110110)

转换回字节将为您提供0b11110110 的“预期”结果

byte notB = unchecked((byte)(~b)); // 0b11110110 = 128 + 64 + 32 + 16 + 4 + 2
Console.WriteLine(notB); // 246

【讨论】:

    【解决方案2】:

    您忘记了前导位也是反转的:

    00001001
    NOT
    11110110
    

    看起来你想屏蔽那些:

    byte b = 9;
    Console.WriteLine(~b & 0xf);  // should output 6
    

    【讨论】:

      猜你喜欢
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 2022-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      相关资源
      最近更新 更多