Home > OS >  Why this narrowing conversion (Maximum long value to byte) has the value of -1?
Why this narrowing conversion (Maximum long value to byte) has the value of -1?

Time:12-22

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

CodePudding user response:

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.

CodePudding user response:

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

  •  Tags:  
  • java
  • Related