C# NOT (~) bit wise operator returns negative values

匿名 (未验证) 提交于 2019-12-03 01:01:02

问题:

Why does C#'s bitwise NOT operator return (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?

How would I do this in C#?

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

回答1:

Bitwise operations return a value of type int (signed). Signed integers use two's-complement to represent negative numbers. Sign extension is used when going from byte to int.

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)

Casting back to byte will give you the "expected" result for 0b11110110

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


回答2:

You forgot that the leading bits are also inverted:

00001001 NOT 11110110

It looks like you want to mask those:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!