我希望将以下C#代码转换为Java。我很难想出一个等价物。
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#方法。
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;
}
答案 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;
}