Why does the bitwise complement operator '~' behave differently in C # and java?

When I execute the code in C # and java, I get a different output. In C #, got the output 254, but in java got the output -2. Why does he behave differently with respect to exit? But I want the same output in java to mean what I want to output 254.

In C # code:

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

Conclusion: 254

In Java code:

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

Output: -2

+4
source share
2 answers

# byte 8- , 0-255. Java 8- , -128-127. -2 () , 254 ( ).

+10

8- Java, & 0xFF

Try

System.out.println(~1 & 0xFF);

System.out.println((byte) ~1 & 0xFF);
0

All Articles