如何将二进制代码简化为java类型代码?

如何将二进制代码简化为java类型代码?,java,casting,bit-shift,Java,Casting,Bit Shift,我得到两个java字节作为输入,它们一起表示一个16位有符号整数。我需要将其转换为一个java整数(当然是有符号的)。我提出了一个“丑陋”的解决方案,包括转换成int,然后转换成short,然后再转换回int。有没有更简洁、更优雅的方法? 我的代码如下: public int convert(byte b1, byte b2){ int i1 = (int) (((b2 << 8) + (b1 & 0xFF)) & 0x0000FFFF); short

我得到两个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;
}
public int convert(字节b1,字节b2){

inti1=(int)((b2这似乎与您的转换器匹配-不确定它是否更简单,但肯定不太详细

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

以下是等效的:

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

@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

return(short)i1;
使用自动加宽会更简单。但我必须在最后得到一个int(不短)(出于传统原因)。
return(short)i1;
与您的最后3行相同。小指咒骂。此外,您不需要在
int i1=(int)…
行中显式转换。
否,返回(短)i1将i1转换为一个短值。它将导致编译器错误,因为函数签名告诉它必须返回int。有趣的解决方案,将尝试。我忘了提到性能并不重要。我需要实时转换成吨的这些数字。
byte[] bytes = ...
ByteBuffer buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
...
short n = buf.readShort(); // Sequential
short m = buf.readShort(354L); // Direct access