我有一个类,有一个名为的变量buffer
,其中包含一个字节数组。我有一个称为的方法readShort
,该方法从缓冲区读取两个字节并将其返回为short。但是,有时它返回负值,我不知道为什么。
这是我的课:
public class InPacket {
private int index;
private byte[] buffer;
public InPacket(byte[] data) {
this.index = 0;
this.buffer = data;
}
public int getLength() {
return buffer.length;
}
public int getAvailable() {
return buffer.length - index;
}
public int getPosition()
{
return index;
}
public void setPosition(int value) throws Exception {
if (value < 0 || value > buffer.length) {
throw new Exception("Value out of range.");
}
this.index = value;
}
private void checkLength(int length) {
if (index + length > buffer.length || length < 0) {
//throw new Exception("Length out of range.");
}
}
public boolean readBoolean() {
checkLength(1);
return buffer[index++] != 0;
}
public byte readByte()
{
checkLength(1);
return buffer[index++];
}
public byte[] readBytes(int count)
{
checkLength(count);
byte[] temp = new byte[count];
System.arraycopy(buffer, index, temp, 0, count);
index += count;
return temp;
}
public short readShort()
{
checkLength(2);
int v1 = buffer[index++];
v1 |= buffer[index++] << 8;
return (short)v1;
}
public int readInt()
{
checkLength(4);
int v1 = buffer[index++];
v1 |= buffer[index++] << 8;
v1 |= buffer[index++] << 16;
v1 |= buffer[index++] << 24;
return v1;
}
public long readLong()
{
checkLength(8);
long v1 = buffer[index++];
v1 |= buffer[index++] << 8;
v1 |= buffer[index++] << 16;
v1 |= buffer[index++] << 24;
v1 |= buffer[index++] << 32;
v1 |= buffer[index++] << 40;
v1 |= buffer[index++] << 48;
v1 |= buffer[index++] << 56;
return v1;
}
public String readString() {
short count = readShort();
return readString(count);
}
public String readString(int count)
{
checkLength(count);
char[] fin = new char[count];
for (int i = 0; i < count; i++)
{
fin[i] = (char)readByte();
}
return new String(fin);
}
public Point readPoint() {
return new Point(readShort(), readShort());
}
public byte[] readRemainingBytes() {
return readBytes(getAvailable());
}
public void skip(int count)
{
checkLength(count);
index += count;
}
public byte[] toArray() {
byte[] fin = new byte[buffer.length];
System.arraycopy(buffer, 0, fin, 0, buffer.length);
return fin;
}
@Override
public String toString() {
String ret = "";
for (int i = 0; i < buffer.length; i++) {
ret += String.format("%02X ", buffer[i]);
}
return ret;
}
}
因此,它可以一直工作到读取较高值的某一点,然后将其返回负值。(-127而不是129)。为什么会发生这种情况,我该怎么做才能解决该问题?
这是我用来阅读短裤的方法:
public final int readUnsignedShort()
throws IOException
{
int ch1 = m_byteArray[m_nCounter++];
int ch2 = m_byteArray[m_nCounter++];
if ( ch1 < 0 )
{
ch1 = ch1 + 256;
}
if ( ch2 < 0 )
{
ch2 = ch2 + 256;
}
return ((ch2 << 8) & 0xFF00) + (ch1 & 0x00FF);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句