Java 如何合并两个整数变量以形成一个长变量
我有一个长类型变量,应该保存到字节缓冲区。由于在Java中,所有的int值都可以放入4个字节,所有的long值都存储在8个字节中,我可以使用一个简单的功能,将整数保存在4个字节中,因此我提出了以下解决方案:Java 如何合并两个整数变量以形成一个长变量,java,Java,我有一个长类型变量,应该保存到字节缓冲区。由于在Java中,所有的int值都可以放入4个字节,所有的long值都存储在8个字节中,我可以使用一个简单的功能,将整数保存在4个字节中,因此我提出了以下解决方案: public class TestApp { static byte [] buffer = new byte[8]; static public void writeInt(int startIndex, int number) { buffer[sta
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));
}
}
公共类TestApp{
静态字节[]缓冲区=新字节[8];
静态公共void writeInt(int startIndex,int number){
缓冲区[startIndex]=(字节)(数字>>24);
缓冲区[startIndex+1]=(字节)(数字>>16&0x000000FF);
缓冲区[startIndex+2]=(字节)(数字>>8&0x000000FF);
缓冲区[startIndex+3]=(字节)(数字&0x000000FF);
}
静态公共int readInt(int startIndex){
返回
(buffer[startIndex]&0xFF)您的问题在这部分:
long a1 = readInt(startIndex);
long a2 = readInt(startIndex+4);
readInt
返回一个int
。它会自动转换为long。转换为long不仅仅是添加四个字节的零。它会将符号位向左扩展
在本例中,a2
是0xb261b0c2
。这意味着它的最高有效位-符号位-是1。因此它被扩展到长0xffffffb261b0c2
当然,当您使用移位的a1
时,结果将始终为0xffffff\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
你应该做的是
long a2 = readInt(startIndex+4) & 0xffffffffL;
这将确保a2
的最重要的四个字节保持为零,因此当您或他们使用移位的a1
Real怀疑论者的答案是正确的。在我看来,您似乎正在尝试重新发明轮子。例如,在long/int/…和字节数组之间已经进行了转换:
long r = 817859255185602L;
byte[] buffer = Longs.toByteArray(r);
long test = Longs.fromByteArray(buffer);
谢谢你在符号位上的解释。我忽略了它的意义。