将C#方法转换为Java

时间:2013-03-17 04:29:03

标签: c# java

我希望将以下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(缓冲区,0)。”我如何让Java等同于工作的C#方法。

错误的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;
}

1 个答案:

答案 0 :(得分: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;
}