How to Make Unsigned Byte in Java

Can we make unsigned byte in Java

I'm not sure I understand your question.

I just tried this and for byte -12 (signed value) it returned integer 244 (equivalent to unsigned byte value but typed as an int):

  public static int unsignedToBytes(byte b) {
return b & 0xFF;
}

public static void main(String[] args) {
System.out.println(unsignedToBytes((byte) -12));
}

Is it what you want to do?

Java does not allow to express 244 as a byte value, as would C. To express positive integers above Byte.MAX_VALUE (127) you have to use a different integral type, like short, int or long.

How to Convert Int to Unsigned Byte and Back

A byte is always signed in Java. You may get its unsigned value by binary-anding it with 0xFF, though:

int i = 234;
byte b = (byte) i;
System.out.println(b); // -22
int i2 = b & 0xFF;
System.out.println(i2); // 234

How to convert an unsigned byte to a signed byte

Found it! You just subtract by 256 if it exceeds by 128.

if (byte >= 128) { byte -= 256; }

Java and unsigned Bytes

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



Related Topics



Leave a reply



Submit