문제

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?

도움이 되었습니까?

해결책 2

This will work

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

다른 팁

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??

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top