Reputation: 1462
I am looking to convert the following bit of C# code to Java. I having a hard time coming up with a equivalent.
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;
}
Here is the Java Code that does not work. The Big challenge is the "BitConverter.ToInt16(buffer,0). How do i get the Java equal of the working C# method.
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;
}
Upvotes: 2
Views: 1273
Reputation: 20585
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;
}
Upvotes: 4