如何简化这种二进制到java类型的代码?

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

我得到两个java字节作为输入,它们一起表示一个16位有符号整数。我需要将它转换为一个单独的java整数(当然是签名)。我想出了一个“丑陋”的解决方案,包括转换为int,然后转换为short,然后转换为int。有更短更优雅的方式吗?我的代码如下:

public int convert(byte b1, byte b2){
    int i1 = (int) (((b2 << 8) + (b1 & 0xFF)) & 0x0000FFFF);
    short s1 = (short) i1;
    int i2 = (int) s1;
    return i2;
}
java casting bit-shift
3个回答
1
投票

这似乎与您的转换器相匹配 - 不确定它是否更简单,但它肯定不那么冗长。

public int convert2(byte b1, byte b2) {
    return new BigInteger(new byte[]{b2,b1}).intValue();
}

1
投票

以下是等效的:

return (short) ((b2 << 8) | (b1 & 0xFF));

byte有一个足够小的范围,可以测试b1b2的所有可能值的等价性:

byte b1 = Byte.MIN_VALUE;
do {
  byte b2 = Byte.MIN_VALUE;
  do {
    assertEquals(convert(b1, b2), convertEquivalent(b1, b2));
  } while (b2++ != Byte.MAX_VALUE);
} while (b1++ != Byte.MAX_VALUE);

Ideone demo


0
投票

@AndTurner可能是您寻求的解决方案。

但是,如果涉及输入流的字节数组或某个文件通道(内存映射文件),则可以使用ByteBuffer。

byte[] bytes = ...
ByteBuffer buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
...
short n = buf.readShort(); // Sequential
short m = buf.readShort(354L); // Direct access
© www.soinside.com 2019 - 2024. All rights reserved.