我试图在Java中翻转一些字节,并且我拥有的功能正常为某些字节工作,并且对其他字节失败。

我正在使用的功能是:

public static int foldInByte(int m, int pos, byte b) {
    int tempInt = (b << (pos * 8));
    tempInt = tempInt & (0x000000ff << (pos * 8));
    m = m | tempInt;
    return m;
}

实现这一点的代码是:

byte[] bitMaskArray = new byte[]{
                            byteBuffer.get(inputIndex),
                            byteBuffer.get(inputIndex + 1),
                            byteBuffer.get(inputIndex + 2),
                            byteBuffer.get(inputIndex + 3)};
                        int tempInt = 0;

                        tempInt = foldInByte(0, 3, bitMaskArray[3]);
                        tempInt = foldInByte(tempInt, 2, bitMaskArray[2]);
                        tempInt = foldInByte(tempInt, 1, bitMaskArray[1]);
                        tempInt = foldInByte(tempInt, 0, bitMaskArray[0]);

                        bitMask = tempInt;

字节正在从字节上读取,字节订单是小末日。

例如,字节00 01 b6 02将位掩码设置为:2B60100-在我的程序中完美工作。

但是,如果字节为A0 01 30 00,则将位掩码设置为:3001A0-它已将最后一个零从位数列为零。

有什么办法可以阻止Java丢弃尾随的零?

我希望这是有道理的。

谢谢

托尼

有帮助吗?

解决方案

零没有被剥离 - 引用的两个示例都是正确的。

  • 00 01 B6 02是2B60100
  • A0 01 30 00是3001A0的4字节小范围

零在那里,但可能没有印刷。 system.out.print呼叫家族将不会打印领先的零数字。

我可能会提到您的方法是必不可少的。这是一种计算相同值的单一方法:

static int extractLittleEndian4(byte[] buf, int index)
{
    int a = buf[index+0]&0xff, b = buf[index+1]&0xff, c = buf[index+2]&0xff, d = buf[index+3]&0xff;
    return a | (b << 8) | (c << 16) | (d << 24);
}

其他提示

看来您已经有一个字节填充了您的字节。您为什么不让字节扣为您逆转字节?只需将字节添加到缓冲区中(如果要添加整数而不是字节,则默认值是默认值),然后在读取整数之前更改顺序。

byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
int output = byteBuffer.getInt(0);

如果您要做的就是逆转字节订单,请让图书馆为您完成工作。如果您碰巧从整数值开始,甚至可以做到这一点:

int input = ...;
int output = Integer.reverseBytes(input);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top