4

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

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • 1
    Helpful: [How does the bitwise complement (~) operator work?](http://stackoverflow.com/questions/791328/how-does-the-bitwise-complement-operator-work) – Soner Gönül Nov 14 '14 at 09:07

2 Answers2

10

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).

Hoopje
  • 12,677
  • 8
  • 34
  • 50
  • I would also emphasize that the operator `~` works the same in Java and C#, the only difference is in how `byte` is converted to String in Java and C#. – kajacx Nov 15 '14 at 19:47
0

To get an unsigned 8-bit value in Java you need to do & 0xFF

Try

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

or

System.out.println((byte) ~1 & 0xFF);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130