Can we make unsigned byte in Java

前端 未结 16 1058
青春惊慌失措
青春惊慌失措 2020-11-22 08:02

I am trying to convert a signed byte in unsigned. The problem is the data I am receiving is unsigned and Java does not support unsigned byte, so when it reads the data it tr

16条回答
  •  礼貌的吻别
    2020-11-22 08:28

    If you want unsigned bytes in Java, just subtract 256 from the number you're interested in. It will produce two's complement with a negative value, which is the desired number in unsigned bytes.

    Example:

    int speed = 255; //Integer with the desired byte value
    byte speed_unsigned = (byte)(speed-256);
    //This will be represented in two's complement so its binary value will be 1111 1111
    //which is the unsigned byte we desire.
    

    You need to use such dirty hacks when using leJOS to program the NXT brick.

提交回复
热议问题