Jason Rich Darmawan
Jason Rich Darmawan

Reputation: 2101

Why java.io.InputStream `read()` method outputs different value if compared with `read(byte[] b)`?

My goal is to decode message, sent by a client to the server through the WebSocket connection. The frame data have length, more on Base Framing Protocol [RFC6455].

I recently found out that read(byte[] b) outputs the entire frame.

For example, when a client send message abcdef to the server

byte[] frame = new byte[1000]
inputStream.read(frame); // [[-127, -122, -69, -122, 95, -5, -38, -28, 60, -97, -34, -32, 0, 0, ....]

However, the first byte should be 129 and the second byte should be 134. Is the only way to read the frame is through loop and use int[] instead of byte[] since the read() method outputs int instead of byte?

int[] frame = new frame[1000];
booean close = false;

frame[0] = inputStream.read();
frame[1] = inputStream.read();

int length = frame[1] & 127;

int pointer = 2;

while (!close) {
  frame[pointer] = inputStream.read();
  if (pointer == length) {
    close = true;
  }
}

Upvotes: 0

Views: 84

Answers (1)

tgdavies
tgdavies

Reputation: 11474

-127 'is' 129, i.e. it's 10000001, which is either number depending on whether it's signed or unsigned.

Read What is “2's Complement”? for more details on the format of signed binary numbers.

So you could use byte[] and convert bytes to int when you need to, e.g.

    public static void main(String... args) {
        byte b = -127;
        int i = b & 0xff;
        System.out.println("b = " + b + " i = " + i);
    }

Upvotes: 2

Related Questions