Home > Net >  Java equivalent of memcpy'ing a char[] to short
Java equivalent of memcpy'ing a char[] to short

Time:03-12

In Java or Kotlin, what would be the equivalent of this C code:

char* data = new char[size]; 
//read file to this array

short version = 0;
memcpy(&version, data, 2);

I tried this:

//java equivalent of the kotlin code below
Integer.parseInt(String(Arrays.copyOfRange(data, 0, 2)))

//kotlin:
data.copyOfRange(0, 2).concatToString().toInt()

but it doesn't work.

ByteBuffer doesn't work as well:

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

CodePudding user response:

Try using ByteBuffer:

byte[] data = new byte[size];
ByteBuffer buffer = ByteBuffer.wrap(data);
short version = buffer.getShort();

If needed you can also change the byte order

  • Related