[英]Java byte buffer getLong() overflows long variable
我正在使用與Java 1.4一起使用的非常裸露的ByteBuffer。 我有一個很小的骨架,基本上只是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);
}
}
在您的getLong方法中,必須將(0xFF&get())強制轉換為長整數,然后才能將其移位超過32位。 您也可以使用長文字(0xFFL)代替整數文字(0xFF)。
這樣做的原因是,“ int && byte”運算的結果類型(0xFF&get())是一個int。 移位操作的規范是這樣的:如果a是int,則“ a << b”實際上將移位“ b模32”位,而如果a是長則“ b <<模64”位。
theLong |= (long) ((0xFF & get()) << (8 * i));
移位從字節傳播的int值,並且只能移位32位位置。
解:
theLong |= ((long) (0xFF & get())) << (8 * i);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.