gpt4 book ai didi

java - 如何连接两个整数变量以形成一个长变量

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:07:26 25 4
gpt4 key购买 nike

我有一个 long 类型的变量,它应该被保存到一个字节缓冲区中。由于在 Java 中所有 int 值都适合 4 个字节,所有 long 值都存储在 8 个字节中,并且我可以访问一个简单的功能,将整数保存在 4 个字节中,我想出了这个解决方案:

public class TestApp {

static byte [] buffer = new byte[8];

static public void writeInt(int startIndex, int number) {
buffer[startIndex] = (byte) (number >> 24);
buffer[startIndex + 1] = (byte) (number >> 16 & 0x000000FF);
buffer[startIndex + 2] = (byte) (number >> 8 & 0x000000FF);
buffer[startIndex + 3] = (byte) (number & 0x000000FF);
}

static public int readInt(int startIndex) {
return
(buffer[startIndex] & 0xFF) << 24 |
(buffer[startIndex+1] & 0xFF) << 16 |
(buffer[startIndex+2] & 0xFF) << 8 |
(buffer[startIndex+3] & 0xFF);
}

static public void writeLong(int startIndex, long number) {
writeInt(startIndex, (int)(number >> 32));
writeInt(startIndex + 4, (int)number);
}

static public long readLong(int startIndex) {
long a1 = readInt(startIndex);
long a2 = readInt(startIndex+4);
long b= a1 << 32;
b |= a2;
return b;
}

public static void main(String []args) {
long r = 817859255185602L;

writeLong(0, r);
long test = readLong(0);

System.out.println(Long.toString(r));
System.out.println(Long.toString(test));
}
}

看到 readLong() 实际上没有完成它应该做的事情,真是令人惊讶。我在编写 readLong()writeLong() 时的想法是,当将一个整数值向左移动 32 位,并将结果与​​下一个整数进行或运算时;结果将成为所需的 long 值。但是这个样本证明我错了。对两个整数进行 or 运算有什么问题?

最佳答案

您的问题出在这部分:

long a1 = readInt(startIndex);
long a2 = readInt(startIndex+4);

readInt 返回一个 int。这会自动转换为 long。转换为 long 并不是简单地添加四个字节的零。它将符号位向左扩展。

在这种情况下,a20xb261b0c2。这意味着它的最高有效位 - 符号位 - 是 1。因此它被扩展为长 0xffffffffb261b0c2

当然,当您将其与移位后的 a1 进行 OR 运算时,结果将始终为 0xffffffff________

你应该做的是

long a2 = readInt(startIndex+4) & 0xffffffffL;

这将确保 a2 的最重要的四个字节将保持为零,因此当您将它们与移位后的 a1 进行或运算时,它们将保持中性。

关于java - 如何连接两个整数变量以形成一个长变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37227579/

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