Java 相当于 memcpy 将 char[] 变短
Java equivalent of memcpy'ing a char[] to short
在 Java 或 Kotlin 中,以下 C++ 代码的等价物是什么:
char* data = new char[size];
//read file to this array
short version = 0;
memcpy(&version, data, 2);
我试过这个:
//java equivalent of the kotlin code below
Integer.parseInt(String(Arrays.copyOfRange(data, 0, 2)))
//kotlin:
data.copyOfRange(0, 2).concatToString().toInt()
但是没用。
ByteBuffer 也不能正常工作:
data[0] is 14
data[1] is 0
ByteBuffer.wrap(data).getShort() is 3584, memcpy is 14
data[2] is -28
data[3] is 45
data[4] is 0
data[5] is 0
ByteBuffer.wrap(data).getInt(2) is -466812928, memcpy is 11748
尝试使用 ByteBuffer
:
byte[] data = new byte[size];
ByteBuffer buffer = ByteBuffer.wrap(data);
short version = buffer.getShort();
如果需要,您还可以更改字节顺序
在 Java 或 Kotlin 中,以下 C++ 代码的等价物是什么:
char* data = new char[size];
//read file to this array
short version = 0;
memcpy(&version, data, 2);
我试过这个:
//java equivalent of the kotlin code below
Integer.parseInt(String(Arrays.copyOfRange(data, 0, 2)))
//kotlin:
data.copyOfRange(0, 2).concatToString().toInt()
但是没用。
ByteBuffer 也不能正常工作:
data[0] is 14
data[1] is 0
ByteBuffer.wrap(data).getShort() is 3584, memcpy is 14
data[2] is -28
data[3] is 45
data[4] is 0
data[5] is 0
ByteBuffer.wrap(data).getInt(2) is -466812928, memcpy is 11748
尝试使用 ByteBuffer
:
byte[] data = new byte[size];
ByteBuffer buffer = ByteBuffer.wrap(data);
short version = buffer.getShort();
如果需要,您还可以更改字节顺序