我正在使用非常简单的骨头ByteBuffer与java 1.4一起使用.我有一个小骨架,基本上只有糟糕的put/getInt()put/getLong()实现.我的问题是,当putInt和getInt工作时,getLong()(我认为它)不起作用.
当我读出第四个字节并将其移入长时间溢出时.但是我所有的变量都很长,所以它不应该溢出.
下面是代码(请记住,这只是一个开始):
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在你的getLong方法中,你必须将(0xFF和get())转换为long,然后才能将它移动超过32位.您还可以使用长文字(0xFFL)而不是int literal(0xFF).
这样做的原因是"int && byte"操作的结果类型(0xFF&get())是一个int.位移操作的规范是这样的,如果a是int,则"a << b"实际上将移位"b模32"位,如果a是long,则"b模64"位.