gpt4 book ai didi

Java 字节缓冲区 getLong() 溢出 long 变量

转载 作者:行者123 更新时间:2023-11-29 10:17:39 25 4
gpt4 key购买 nike

我正在研究一个非常简单的 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);
}

}

最佳答案

在您的 getLong 方法中,您必须先将 (0xFF & get()) 转换为长整数,然后才能将其移动超过 32 位。您还可以使用长文字 (0xFFL) 而不是 int 文字 (0xFF)。

原因是“int && byte”操作(0xFF & get())的结果类型是 int。移位操作的规范是这样的,如果 a 是 int,则“a << b”实际上将移动“b modulo 32”位,如果 a 是 long,则“b modulo 64”位。

关于Java 字节缓冲区 getLong() 溢出 long 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13605611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com