Can we make unsigned byte in Java

前端 未结 16 1268
青春惊慌失措
青春惊慌失措 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:38

    Yes and no. Ive been digging around with this problem. Like i understand this:

    The fact is that java has signed interger -128 to 127.. It is possible to present a unsigned in java with:

    public static int toUnsignedInt(byte x) {
        return ((int) x) & 0xff;
    }
    

    If you for example add -12 signed number to be unsigned you get 244. But you can use that number again in signed, it has to be shifted back to signed and it´ll be again -12.

    If you try to add 244 to java byte you'll get outOfIndexException.

    Cheers..

提交回复
热议问题