Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the bitwise complement operator '~' behave differently in c# and java? [duplicate]

When I execute the code in c# and java, I get different output. In c#, got the output 254 but in java got the output -2. Why does it behave differently in term of output? But I want the same output in java means I want output 254.

In c# code:

static void Main(string[] args)
{
     byte value = 1;
     System.Console.WriteLine("Value after conversion {0}", (byte)(~value));
}

Output : 254

In Java code:

public static void main(String[] args) {
        byte value = 1;
        System.out.println((byte)(~value ));
}

Output : -2

like image 385
user3906847 Avatar asked Dec 25 '22 02:12

user3906847


1 Answers

In C# byte denotes an unsigned 8-bit integer value, i.e. its range is 0-255. In Java, however, a byte is a signed 8-bit integer value, i.e. its range is -128-127. -2 (signed) has the same binary representation as 254 (unsigned).

like image 136
Hoopje Avatar answered Dec 28 '22 10:12

Hoopje