How are integers cast to bytes in Java?

后端 未结 8 1222
我在风中等你
我在风中等你 2020-11-27 21:02

I know Java doesn\'t allow unsigned types, so I was wondering how it casts an integer to a byte. Say I have an integer a with a value of 255 and I cast the integer to a byte

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 21:41

    for (int i=0; i <= 255; i++) {
        byte b = (byte) i;    // cast int values 0 to 255 to corresponding byte values 
        int neg = b;     // neg will take on values 0..127, -128, -127, ..., -1
        int pos = (int) (b & 0xFF);  // pos will take on values 0..255
    }
    

    The conversion of a byte that contains a value bigger than 127 (i.e,. values 0x80 through 0xFF) to an int results in sign extension of the high-order bit of the byte value (i.e., bit 0x80). To remove the 'extra' one bits, use x & 0xFF; this forces bits higher than 0x80 (i.e., bits 0x100, 0x200, 0x400, ...) to zero but leaves the lower 8 bits as is.

    You can also write these; they are all equivalent: int pos = ((int) b) & 0xFF; // convert b to int first, then strip high bits int pos = b & 0xFF; // done as int arithmetic -- the cast is not needed

    Java automatically 'promotes' integer types whose size (in # of bits) is smaller than int to an int value when doing arithmetic. This is done to provide a more deterministic result (than say C, which is less constrained in its specification).

    You may want to have a look at this question on casting a 'short'.

提交回复
热议问题