Convert unsigned byte to signed byte

前端 未结 5 1862
抹茶落季
抹茶落季 2020-12-17 21:37

Is there an easy and elegant way to convert an unsigned byte value to a signed byte value in java? For example, if all I have is the int value 240 (in binary (24 bits + 1111

5条回答
  •  爱一瞬间的悲伤
    2020-12-17 22:07

    Java only supports signed bytes so whenever you place a value in a byte, its assumed to be signed.

    byte b = (byte) 240;
    

    However if you want to store an unsigned byte, you need to handle this yourself. (i.e. Java doesn't support it but you can do it)

    For operations like +, -, *, <<, >>>, ==, !=, ~ you don't need to change anything, For operations like <, > you need to have make minor adjustments, and for operations like /, % you need to use a larger data type.

    A common alternative is to use a larger data type like int to store values 0 - 255. There is not much disadvantage in doing so.

提交回复
热议问题