why byte is in range -127 - 127

edited August 2015 in Programming Questions

The Most strange thing I have found in Processing is the range of the Byte type: -127 to 127. Why?? Normally, also in Arduino, Byte is a number between 0 and 255.

For example I want to send the byte 250 (in decimal) through a serial port.

Show me on this simple code the trick:

byte mybyte = ???; myport.write(mybyte);

Tagged:

Answers

  • edited August 2015
    • Correcting: primitive datatype byte is -128 to 127 range!
    • Processing, being just a toolkit, can't do anything about it. It's Java language's specification.
    • Arduino runs upon C. And uses unsigned char datatype instead of Java's byte, which is signed.
    • However, nothing is lost. For example: unsigned char 250 becomes byte -6:
      println((byte) 250);

    http://docs.Oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

  • edited August 2015
    byte b = (byte) 250;
    int  i = b & 0xff;
    
    println(b, i); // -6  250
    exit();
    
  • Because all numerical types in Java (except char, which is only "half" a numerical type) are signed. An unfortunate choice, but we have to live with it.

Sign In or Register to comment.