Equivalent of BitConverter.ToUInt16 of C# for Java

一世执手 提交于 2020-07-03 13:25:48

问题


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?


回答1:


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();
}


来源:https://stackoverflow.com/questions/62648624/equivalent-of-bitconverter-touint16-of-c-sharp-for-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!