Signed and Unsigned Bytes in Processing

bytes.jpg

Java, and therefore Processing, interprets a byte as being a number between -127 and +127. Other environments, including the PIC, interpret a byte as being a number between 0 and 255. To be exact, Java uses only signed bytes and the PIC uses only unsigned bytes, so translations have to happen when the two talk to each other.

Here’s how to get your numbers back and forth intact:

When sending from Processing, create an int and then cast it as a byte before sending it out, like this:

int myValue = 200;   // a number you want to send out (must be between 0 and 255)
byte myValueByte = (byte) myValue;  // cast the int as a byte, now it's ready to send

When receiving a byte value from the PIC, Java will interpret the incoming data as a signed byte. To convert it to an unsigned byte between 0 and 255, here’s a handy snippet of binary math:

byte myReceivedByte = -2; // this negative signed byte is the same as an unsigned 254
myReceivedInt = myReceivedByte & 0xFF; // this binary math operation effectively restores the byte to its unsigned state

I got some good info on this from conversations with Dan O’Sullivan, Jeff LeBlanc and from the Internet

1 thought on “Signed and Unsigned Bytes in Processing”

Comments are closed.

Scroll to Top