简体   繁体   中英

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM