问题
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