I am developing an app which communicate with a C Program running on windows server, This program is developed using Visual Studio (if this information can be of any help).
The server sends me an integer through socket communication, Before sending server does following things:-
- Declare an int
- Assign it some value
- copy 2 bytes to a char * (say buffer), using memcpy
- Add some more data to that buffer
- Send that buffer
Now at receiving end I have java implementation, so can't use memcpy directly, I have used
short mId = java.nio.ByteBuffer.wrap(recvBuf, 0, 2).order(ByteOrder.LITTLE_ENDIAN).getShort();
which works, fine but this part of code is called in every few miliseconds, So I am trying to optimize it.. I have also used
short mId =(short)(recvBuf[0] + recvBuf[1]*128);
Which also works fine but I doubt whether it will work if the number increases in future. What is the best way to do the repeat of memcpy in java ?
I have visited this thread but that is not of much help,
EDIT I implemented following four methods which worked for me,
public class CommonMethods {
/*
* Returns the byte[] representation of an int in Little Endian format
*
* @param value that should be converted to byte[]
*/
public static byte[] toByteArray(int value) {
return new byte[] { (byte) value, (byte) (value >> 8), (byte) (value >> 16), (byte) (value >> 24) };
}
/*
* Returns the int in LittleEndian value of the passed byte[]
*
* @param bytes is the input byte[]
*
* @param offset is the offset to start
*/
public static int getInt(byte[] bytes, int offset, int length) {
int retValue = (bytes[offset] & 0xFF);
byte bVal;
for (int i = 1; i < length; i++) {
bVal = bytes[offset + i];
retValue |= ((bVal & 0xFF) << (8 + (8 * (i - 1))));
}
return retValue;
}
/*
* Returns the int in BigEndian from the passed byte[]
*
* @param bytes is the byte[]
*/
public static int getIntBigEndian(byte[] bytes, int offset, int length) {
int retValue = (bytes[offset + length - 1] & 0xFF);
for (int i = 1; i < length; i++) {
retValue |= ((bytes[offset + length - 1 - i] & 0xFF) << (8 + (8 * (i - 1))));
}
return retValue;
}
/*
* Returns the byte[] representation of an int in Big Endian format
*
* @param value that should be converted to byte[]
*/
public static byte[] toByteArrayBigEndian(int value) {
return new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value };
}
}