Adalher2478
Adalher2478

Reputation: 35

Equivalent of BitConverter.ToUInt16 of C# for Java

My question is about Java

What is the equivalent of BitConverter.ToUInt16 for Java?

I am trying to translate this method of C#:

public static implicit operator ushort(HashlinkReader p)
        {
            ushort tmp = BitConverter.ToUInt16(p.Data.ToArray(), p.Position);
            p.Position += 2;
            return tmp;
        }

to Java:

public static int convertToInt(HashlinkReader p)
    {
        byte[] byteArray = new byte[p.Data.size()];
        for (int index = 0; index < p.Data.size(); index++) {
            byteArray[index] = p.Data.get(index);
        }
        int tmp = toInt16(byteArray, p.Position);
        p.Position += 2;
        return tmp;
    }
    
    public static short toInt16(byte[] bytes, int index) //throws Exception
    {
        return (short)((bytes[index + 1] & 0xFF) | ((bytes[index] & 0xFF) << 0));
        //return (short)(
        //        (0xff & bytes[index]) << 8 |
        //                (0xff & bytes[index + 1]) << 0
        //);
    }

But I know that's wrong. How would be right?

Upvotes: 0

Views: 470

Answers (1)

VGR
VGR

Reputation: 44414

You want a ByteBuffer:

public static short toInt16(byte[] bytes, int index) {
    return ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder())
        .position(index).getShort();
}

For Java 7, the method calls are the same, but due to their return types, they need to be split into multiple lines:

public static short toInt16(byte[] bytes, int index) {
    ByteBuffer buffer =
        ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder());
    buffer.position(index);
    return buffer.getShort();
}

Upvotes: 3

Related Questions