2

I used this site for conversion: https://www.binaryhexconverter.com/binary-to-decimal-converter

9223372036854775807 is represented as 0111111111111111111111111111111111111111111111111111111111111111

And a byte takes up 1 byte, which is 8 bit, so the last 8 bit is: 11111111 Converting this back to a number using the website linked above I get 255, not -1.

Please see my code.

Thank you very much for helping me out.

   long l = 9223372036854775807L;
   System.out.println("Value of B: " + l);

   byte b = (byte) (l);
   System.out.println("Value of B: " + b);

This has the following result:

Value of B: 9223372036854775807
Value of B: -1
Johnes
  • 49
  • 5
  • 8
    Did you look at the range of values that a `byte` can hold in Java? See https://docs.oracle.com/javase/specs/jls/se10/html/jls-4.html#jls-4.2.1 – Jon Skeet Dec 21 '21 at 20:20
  • 2
    I do not know about that website, but in Java a byte with binary `11111111` is `-1` (8 bit signed two complement integer) - not only in Java: [Wikipedia](https://en.wikipedia.org/wiki/Two%27s_complement) – user16320675 Dec 21 '21 at 20:33

2 Answers2

2

This is perfectly normal, because in Java bytes go from -128 to 127, not from 0 to 255. -1 in a Java signed byte corresponds to 255 in an unsigned byte.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Isn't the most significant bit a sign bit? So -1 in a signed byte would be 10000001? Or am I mixing it up with C++... – Tyler V Dec 21 '21 at 20:35
  • 1
    @TylerV You are mixing it up. In [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement), −1 is binary 11111111. – MC Emperor Dec 21 '21 at 20:41
  • Thank you so it basically depends only if a byte is signed or unsigned (so if it is interpreted for negative / positive range as well or the whole range is on the non negative area) So the website I used calculated bytes for the latter case, while java's byte falls under the first case. Thats why a small recalculation is needed using a table from the linked source. – Johnes Dec 23 '21 at 13:20
0
byte byteVal = (byte)238; // -18
int intVal = byteVal; // sign extended to maintain 2's complement value
System.out.println(byteVal); 
System.out.println(intVal);

prints

-18
-18
  • To print a byte as an unsigned value, AND it with 0xFF (255).
  • the byte is converted to an int as above.
  • the ANDing of the value preserves the lower 8 bits.
System.out.println(byteVal&0xFF);

prints

238

WJS
  • 36,363
  • 4
  • 24
  • 39