2

我希望将以下 C# 代码转换为 Java。我很难想出一个等价物。

工作 C# 代码:

private ushort ConvertBytes(byte a, byte b, bool flip)
{
    byte[] buffer = new byte[] { a, b };
    if (!flip)
    {
        return BitConverter.ToUInt16(buffer, 0);
    }
    ushort num = BitConverter.ToUInt16(buffer, 0);
    //this.Weight = num;
    int xy = 0x3720;
    int num2 = 0x3720 - num;
    if (num2 > -1)
    {
        return Convert.ToUInt16(num2);
    }
    return 1;
}

这是不起作用的Java代码。最大的挑战是“BitConverter.ToInt16(buffer,0)。我如何获得与工作 C# 方法相等的 Java。

错误的 Java 代码:

private short ConvertBytes(byte a, byte b, boolean flip){
    byte[] buffer = new byte[] { a, b };
    if (!flip){
        return  (short) ((a << 8) | (b & 0xFF));
    }
    short num = (short) ((a << 8) | (b & 0xFF));
    //this.Weight = num;
    int num2 = 0x3720 - num;
    if (num2 > -1){
        return (short)num2;
    }
    return 1;
}
4

1 回答 1

4
private short ConvertBytes(byte a, byte b, boolean flip){

    ByteBuffer byteBuffer = ByteBuffer.allocate(2);
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byteBuffer.put(a);
    byteBuffer.put(b);
    short num = byteBuffer.getShort(0);

    //this.Weight = num;
    int num2 = 0x3720 - num;
    if (num2 > -1){
        return (short)num2;
    }
    return 1;
}
于 2013-03-17T04:43:10.493 回答