Java and unsigned Bytes [duplicate]

最后都变了- 提交于 2019-12-01 21:10:11

There is no distinction in Java between signed and unsigned bytes. Both of the following will assign the same value to a byte:

byte i = (byte)160;
byte j = (byte)-96;

Its up to you as a developer to treat them as signed or unsigned when you print them out. The default is to print them signed, but you can force them to print unsigned by converting them to an integer in an unsigned manner.

System.out.println(i); // -96
System.out.println(0xff&i); // 160

If you want to know how bytes can represent both negative and positive numbers at the same time, read this article on two’s complement arithmetic in Java

Sending -96 is the correct behavior. Signed and unsigned bytes are different when they're printed out, but not in the bit representation, and they should not make a difference when they are received by another server.

There is no System.out.println(byte). The closest is System.out.println(int). This means your byte values are converted to ints. The conversion extends the high bit, resulting in a negative number.

This following code will demonstrate my point:

byte[] data =
{
    (byte)0x01,
    (byte)0x02,
    (byte)0x7F,
    (byte)0x80
};

for (byte current : data)
{
    String output = String.format("0x%x, 0x%x", current, (int)current);
    System.out.println(output);
}

If you want to use System.out.println to see your byte values, mask off the top three bytes of the integer value, something like this:

System.out.println(((0x000000FF & (int)current);

Bytes are not signed or unsigned by themselves. They are interpreted as such when some operations are applied (say, compare to 0 to determine sign). The operations can be signed and unsigned, and in Java, only signed byte operations are available. So the code you cited is useless for the question - it sends bytes but does not do any operation. Better show the code which receives bytes. One correct and handy method is to use java.io.InputStream.read() method which returns byte as an integer in the range 0...255.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!