将2个整数值加长

问题描述 投票:0回答:1

我接手了部分实施规范的项目。我有一条消息涉及各个领域。字段之一的ID(称为DestinationID)的类型为long。在此ID中,它表示前4个字节(让我们将其称为左侧)代表某物,而其他4个字节(让我们将其称为右侧)代表另一件事。目前,它已实现为2个整数。考虑到我有这两个整数,是否有办法将其放在一起以获得原始的长值?同样,这些字段是小端,因此将2个整数读取为小端。而且当放在一起时,我也想加一点尾音。我已经进行了反复试验,到目前为止,以下是我的结果。请指出您看到的任何错误。谢谢。

    int left = 262388740;  // 1st 4 bytes
    int right = 671091961; // Rest of 4 bytes

    long destinationID = ((right) << 32) | (left & 0xffffffffL); // Trying to put the 2 together to get the long value

    //Expected - f9 0c 00 28  04 bc a3 0f
    //Received - 28 00 0c f9  0f a3 bc 04 

打印(Long.toHexString(destinationID)时,没有得到期望值。他们似乎倒转了。

java bit-manipulation endianness bit-shift
1个回答
0
投票

您的字节正在用LITTLE_ENDIAN写入。注意,f9 0c 00 2828 00 0c f9相反。我会[[prefer ByteBuffer而不是直接位摆弄。喜欢,

ByteBuffer
输出(根据要求)

int left = 262388740; int right = 671091961; ByteBuffer bb = ByteBuffer.allocate(8); bb.putInt(left); bb.putInt(right); bb.order(ByteOrder.LITTLE_ENDIAN); long r = bb.getLong(0); System.out.println(Long.toHexString(r));

© www.soinside.com 2019 - 2024. All rights reserved.