0

In a java programe, people store data in a byte array, and the first two byte were used to store the length of data,

byte[] buffer = new byte[100000];
int size = data.getBytes().length;

buffer[0] = (byte)((size >> 8 ) &  0xff);
buffer[1] = (byte)(size & 0xff);

now given value of buffer[0] and buffer[1], how to get size back?

CaiNiaoCoder
  • 3,169
  • 9
  • 51
  • 79

2 Answers2

0

All such things are described in DataInputStream/DataOutputStream java classes a long time ago. More specifically in your task it will be:

return (short)(((int)(buffer[0] & 0xff) << 8) + ((int)(buffer[1] & 0xff) << 0));
Andremoniy
  • 32,711
  • 17
  • 122
  • 230
0
public int getSize(byte [] buffer)
{
  return (buffer[0] << 8) | (buffer[1] << 0);
}
ortis
  • 2,143
  • 2
  • 13
  • 18