2

I am looking to convert the following bit of C# code to Java. I having a hard time coming up with a equivalent.

Working C# Code:

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.

Java Code that is Wrong:

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;
}
5
  • 2
    BitConverter uses little endian, so the first byte is the LSB. Commented Mar 17, 2013 at 4:32
  • possible duplicate of 2 bytes to short java Commented Mar 17, 2013 at 4:37
  • Noting also that Java doesn't have an unsigned short: stackoverflow.com/questions/1841461/unsigned-short-in-java Commented Mar 17, 2013 at 4:38
  • Hmm... Alvin and Chris. I am not very clear on what Little endian and how i can use it to solve my issue. Commented Mar 17, 2013 at 4:46
  • Endianness - en.wikipedia.org/wiki/Endianness Commented Mar 17, 2013 at 5:51

1 Answer 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;
}
Sign up to request clarification or add additional context in comments.

6 Comments

u the man! thanks!! this did the trick and now i can sleep without thinking of code
@codeNinja I would downvote your comment if ever it was possible.
@Guillaume - its ok! i am sure he is just saying that for sense of humor.
@Guillaume did i offend someone here? I was just joking. @ AppDeveloper I really do appreciate the help. I was truly stuck. Thanks again
@codeNinja My comment was about your "now I can sleep without thinking of code" :-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.