我正在开发一个非常简单的 ByteBuffer,用于 java 1.4。我有一个小骨架,基本上只是 put/getInt() put/getLong() 的实现很差。我的问题是,虽然 putInt 和 getInt 有效,但 getLong() (我认为是)不起作用。
当我读出第四个字节并将其转换为 long 时,它会溢出。但是我所有的变量都很长,所以它不应该溢出。
下面是代码(请记住,这只是一个开始):
public class ByteBuffer {
private byte[] buffer;
private int first = 0;
private int last = 0;
private int size;
private int elements;
public ByteBuffer(int size) {
this.size = size;
buffer = new byte[size];
}
public void putInt(int theInt) {
for (int i = 0; i < 4; i++) {
put((byte) (theInt >>> (8 * i)));
}
}
public int getInt() {
int theInt = 0;
for (int i = 0; i < 4; i++) {
theInt |= (0xFF & get()) << (8 * i);
}
return theInt;
}
public void putLong(long theLong) {
for (int i = 0; i < 8; i++) {
put((byte) (theLong >>> (8 * i)));
}
}
public long getLong() {
long theLong = 0L;
for (int i = 0; i < 8; i++) {
theLong |= (long) ((0xFF & get()) << (8 * i));
}
return theLong;
}
public void put(byte theByte) {
buffer[last++] = theByte;
if (last == size) {
last = 0;
}
elements++;
}
public byte get() {
byte theByte = buffer[first++];
if (first == size) {
first = 0;
}
elements--;
return theByte;
}
public byte[] array() {
return (byte[]) buffer.clone();
}
/**
* @param args
*/
public static void main(String[] args) {
ByteBuffer buff = new ByteBuffer(512);
buff.putLong(9223372036854775807L);
buff.putLong(-9223372036854775808L);
System.out.println(9223372036854775807L);
System.out.println(-9223372036854775808L);
long l1 = buff.getLong();
long l2 = buff.getLong();
System.out.println(l1);
System.out.println(l2);
}
}