0

see example below. I was either expecting it to be 1 or 249 if we account for the whole bits in the byte type.

I read the sources but I can't figure out why I am not able to grasp it.

byte num1 = 6;
byte num2 = 12;
Assert.IsTrue(~num1 == 1);
Assert.IsTrue(~num2 == 3);
Backs
  • 24,430
  • 5
  • 58
  • 85
AmandaSai98b
  • 485
  • 1
  • 7
  • 17
  • Does this answer your question? [C# NOT (~) bit wise operator returns negative values](https://stackoverflow.com/questions/37881537/c-sharp-not-bit-wise-operator-returns-negative-values) – Charlieface Jan 09 '22 at 13:11

1 Answers1

2

~ operator converts type to int. If you want byte - use cast:

byte num1 = 6;
byte num2 = 12;
Console.WriteLine((byte)~num1);
Console.WriteLine((byte)~num2);
Backs
  • 24,430
  • 5
  • 58
  • 85
  • Wow, I guess I should have paid attention to that. But why would (int)~num1 be -7 – AmandaSai98b Jan 09 '22 at 07:11
  • @AmandaSai98b `(byte)6` in binary is `110`, `(int)6` in binary is `00000000000000000000000000000110`, `(int)~6` in binary is `11111111111111111111111111111001` that is `-7` as signed integer – Backs Jan 09 '22 at 10:33