Java implicit conversion of int to byte

后端 未结 5 1838
难免孤独
难免孤独 2021-01-17 20:45

I am about to start working on something the requires reading bytes and creating strings. The bytes being read represent UTF-16 strings. So just to test things out I wante

相关标签:
5条回答
  • 2021-01-17 21:12

    If you use a number without a hint (e.g. 1234L for a long) the compiler assumes an integer. The value 0xffffffff is an integer with value -1 which can be cast to byte without a warning.

    0 讨论(0)
  • 2021-01-17 21:13

    Because 0xffffffff is the number -1 and -1 can be interpreted as a byte.

    0 讨论(0)
  • 2021-01-17 21:28

    0xff is the same as writing 0x000000ff, not 0xffffffff. So that's your issue; the integer is a positive number (255), but the byte (if converted bit-for-bit) would be a negative number (-1). But 0xffffffff is -1 both as an int and as a byte.

    0 讨论(0)
  • The key thing to remember here is that int in Java is a signed value. When you assign 0xffffffff (which is 2^32 -1), this is translated into a signed int of value -1 - an int cannot actually represent something as large as 0xffffffff as a positive number.

    So for values less than 0x80 and greater than 0xFFFFFF80, the resulting int value is between -128 and 127, which can unambiguously be represented as a byte. Anything outside that range cannot be, and needs forcing with an explicit cast, losing data in the process.

    0 讨论(0)
  • 2021-01-17 21:31

    Because int are signed and 0xffffffff represent -1, and 0xff represent an integer of value 255, which not lie into -128 (0x80) +127 (0x7f) range of a byte.

    0 讨论(0)
提交回复
热议问题