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);
CodePudding user response:
~ 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);
CodePudding user response:
When doing bitwise operation, you can use the following method to print the bits. In addition, the compiler gives an error Argument 1: cannot convert from 'int' to 'byte' when no byte conversion is done.
using System;
public class Program
{
public static string GetBitsAsString(byte b)
{
return Convert.ToString(b, 2).PadLeft(8, '0');
}
public static void Main()
{
byte num1 = 6, num2 = 12;
Console.WriteLine(GetBitsAsString(num1) "\t" GetBitsAsString(num2));
Console.WriteLine(GetBitsAsString((byte)~num1) "\t" GetBitsAsString((byte)~num2));
}
}
This code produces the following output:
00000110 00001100
11111001 11110011
