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,269
  • 9
  • 52
  • 82

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
  • 34,031
  • 20
  • 135
  • 241
0
public int getSize(byte [] buffer)
{
  return (buffer[0] << 8) | (buffer[1] << 0);
}
ortis
  • 2,203
  • 2
  • 15
  • 18