Byte size shortened

Hello, i’m trying to rebuild a float number sent on a serial line.
I had trouble working on a bitwise operation.

Code :

I expected a byte to be 8bits of length but I can only fill the array with 4bits values (Ex : 0xF)

See the byte processing reference :

Datatype for bytes, 8 bits of information storing numerical values from 127 to -128. Bytes are a convenient datatype for sending information to and from the serial port and for representing letters in a simpler format than the char datatype. The first time a variable is written, it must be declared with a statement expressing its datatype. Subsequent uses of this variable must not reference the datatype because Processing will think the variable is being declared again.

So my question is why the byte definition declares a 4bits variable ?

Thank you.

1 Like
// GoToLoop (2019/Sep/02)

import java.nio.ByteBuffer;
import java.nio.FloatBuffer;

static final int BYTES = Float.BYTES;

final byte[] bytes = new byte[BYTES];
final FloatBuffer buf = ByteBuffer.wrap(bytes).asFloatBuffer();

float f;

void setup() {
  println(buf.order(), java.nio.ByteOrder.nativeOrder(), ENTER);

  bytes[0] = (byte) 0xf0;
  bytes[1] = (byte) 0xaa;
  bytes[2] = (byte) 0xf8;
  bytes[3] = (byte) 0x30;


  f = bytes[0] << 030 | bytes[1] << 020 | bytes[2] << 010 | bytes[3];
  println(f); // -2000.0

  f = buf.get(0);
  println(f); // -4.2329994E29


Actually you can use up to 0x7F, which is the hex value for 127. And you can use -0x80, hex for -128. So the entire signed range of the byte is definable in hex, it just doesn’t work the way you expect it to.

println("JAVA number range");
println("System     : " + System.getProperty("") + "  " + System.getProperty("os.version") + "  " + System.getProperty("os.arch") );
println("JAVA       : " + System.getProperty("java.home")  + " rev: " +javaVersionName);

println("byte     min: "+Byte.MIN_VALUE+   "\t\t\t max: "+Byte.MAX_VALUE);
println("short    min: "+Short.MIN_VALUE+  "\t\t\t max: "+Short.MAX_VALUE);
println("int      min: "+Integer.MIN_VALUE+"\t\t max: "+Integer.MAX_VALUE);
println("long     min: "+Long.MIN_VALUE+   "\t max: "+Long.MAX_VALUE);
println("float    min: "+Float.MIN_VALUE+  "\t\t\t max: "+Float.MAX_VALUE);
println("double   min: "+Double.MIN_VALUE+ "\t\t\t max: "+Double.MAX_VALUE);

Why is it impossible to complete a byte with a value superior to 0x7F ?

println(Byte.MIN_VALUE, Byte.MAX_VALUE, Byte.SIZE); // -128, 127, 8
println(hex(Byte.MIN_VALUE), hex(Byte.MAX_VALUE), (byte) 0x80); // 80, 7F, -128
1 Like

Because that is the highest number you can store in a signed byte. Add 1 and you get -0x80. Hex literals are still signed.