Question

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?

Was it helpful?

Solution 2

This will work

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

OTHER TIPS

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.

For a byte b , b & 0xFF will return the unsigned integer value .. will that be okay for you??

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top