Reputation: 163
I need to write a java program that will send byte through serial port. I am using the rxtx library. The problem is that in Java everything is signed, and in one byte I need to send 0xfc
, but in Java this is signed, and it defined as -4. So how can I make an unsigned byte in java, so that in one byte I can send from 0 to 255?
Upvotes: 0
Views: 904
Reputation: 35557
This will work
public static int unsignedToBytes(byte b) {
return b & 0xFF;
}
Upvotes: 0
Reputation: 54672
For a byte b
, b & 0xFF
will return the unsigned integer value .. will that be okay for you??
Upvotes: 0
Reputation: 1500275
It's fine - you can just cast where required. If you have an API which lets you send bytes, and you send a byte of -4 in Java, the bit pattern will be the same as for an unsigned byte 0xfc.
If you have a value as an int
or short
in the range 0-255, just cast that to byte
, and again it will represent the right bit pattern, even though the value will become negative if the original value was above 127.
Upvotes: 3