I know there is a missing cast to long, but is there a better way to do this which is less confusing than the shown approch.
static long getLong(byte[] sourceBytes, int sourceBytesIndex, int numOfBytesToConvert)
{
long longValue = 0;
longValue = (sourceBytes[sourceBytesIndex] & 0xFF) +
((sourceBytes[sourceBytesIndex + 1] & 0xFF) << 8);
if (numOfBytesToConvert > 2)
{
longValue += ((sourceBytes[sourceBytesIndex + 2] & 0xFF) << 16) +
((sourceBytes[sourceBytesIndex + 3] & 0xFF) << 24);
if (numOfBytesToConvert > 4)
{
longValue += ((sourceBytes[sourceBytesIndex + 4] & 0xFF) << 32) +
((sourceBytes[sourceBytesIndex + 5] & 0xFF) << 40);
if (numOfBytesToConvert > 6)
{
longValue += ((sourceBytes[sourceBytesIndex + 6] & 0xFF) << 48) +
((sourceBytes[sourceBytesIndex + 7] & 0xFF) << 56);
}
}
}
return longValue;
}
I prefer to use ByteBuffers, you can also use a switch statement.
The ByteBuffer handles both byte endianess as well the position and the end of usable bytes in the buffer. (Using limit())
I tend to prefer direct ByteBuffers as there can be large without using much heap and are faster than a
byte[]when using the native byte order.