How are integers cast to bytes in Java?

后端 未结 8 1209
我在风中等你
我在风中等你 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:32

    Just a thought on what is said: Always mask your integer when converting to bytes with 0xFF (for ints). (Assuming myInt was assigned values from 0 to 255).

    e.g.

    char myByte = (char)(myInt & 0xFF);
    

    why? if myInt is bigger than 255, just typecasting to byte returns a negative value (2's complement) which you don't want.

提交回复
热议问题