Bug #302

ByteUtils.convertMultiByteToLong(byte[]) is wrong

Added by Philipp Buluschek over 3 years ago.

Status:New Start date:02/17/2015
Priority:Normal Due date:
Assignee:- % Done:

0%

Category:- Spent time: -
Target version:-
Has a patch:No Has license agreement signed:No

Description

The conversion method from a byte[] to a long in ByteUtils is wrong.
See: ByteUtils.convertMultiByteToLong(byte[]).

Test case:

@Test
public void testConvertMultibyteToLong() throws Exception {
  byte[] d = new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01};
  long l = ByteUtils.convertMultiByteToLong(d);
  assertEquals(1L, l); // fails with value 256

  d = new byte[]{0x01,0x23,0x45,0x67,(byte) 0x89,(byte) 0xAB,(byte) 0xCD,(byte) 0xEF};
  long long1 = ByteUtils.convertMultiByteToLong(d);
  assertEquals(81985529216486895L, long1);
}

A possible correct implementation uses:

long val = bytes[0] & 0xFF;
for (int i = 1; i < bytes.length; i++) {
  val = val << 8;
  val += bytes[i] & 0xFF;
}
return val;

Also available in: Atom PDF